diff --git a/htdocs/admin/tools/dolibarr_export.php b/htdocs/admin/tools/dolibarr_export.php
index f1ac3dfc1212525b7a47035b0cc205b68cf15bd7..8fc78e725023aefdc4a5c02788418765c12a99d1 100644
--- a/htdocs/admin/tools/dolibarr_export.php
+++ b/htdocs/admin/tools/dolibarr_export.php
@@ -268,7 +268,7 @@ print $langs->trans("BackupDescY").'<br><br>';
 
                                 <div class="formelementrow"><input type="checkbox" name="nobin_disable_fk"
                                         value="yes" id="checkbox_disable_fk" checked="checked" /> <label
-                                        for="checkbox_disable_fk"> <?php echo $langs->trans("CommandsToDisableForeignKeysForImport"); ?><?php print img_warning('Mandatory if you want to be able to restore your sql dump later'); ?></label>
+                                        for="checkbox_disable_fk"> <?php echo $langs->trans("CommandsToDisableForeignKeysForImport"); ?> <?php print img_info('Mandatory if you want to be able to restore your sql dump later'); ?></label>
                                 </div>
                             </fieldset>
 
diff --git a/htdocs/cashdesk/tpl/menu.tpl.php b/htdocs/cashdesk/tpl/menu.tpl.php
index 44d62f54af4be40aee3ea294ee7ecaad5f9d6d32..78fbc8a4f7466290c8d122716f5261a85e83e69f 100644
--- a/htdocs/cashdesk/tpl/menu.tpl.php
+++ b/htdocs/cashdesk/tpl/menu.tpl.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2008-2010 Laurent Destailleur   <eldy@uers.sourceforge.net>
  * Copyright (C) 2009      Regis Houssin         <regis@dolibarr.fr>
  * Copyright (C) 2011      Juanjo Menent         <jmenent@2byte.es>
+ * Copyright (C) 2012      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
@@ -58,8 +59,6 @@ if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && $conf->stock->enabled)
 $langs->load("cashdesk");
 $langs->load("main");
 
-$logout='<img class="login" border="0" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/logout.png" title="'.dol_escape_htmltag($langs->trans("Logout")).'">';
-
 print '<div class="menu_bloc">';
 print '<ul class="menu">';
 // Link to new sell
@@ -68,7 +67,7 @@ print '<li class="menu_choix1"><a href="affIndex.php?menu=facturation&id=NOUV"><
 print '<li class="menu_choix2"><a href=".." target="backoffice"><span>'.$langs->trans("BackOffice").'</span></a></li>';
 // Disconnect
 print '<li class="menu_choix0">'.$langs->trans("User").': '.$_SESSION['prenom'].' '.$_SESSION['nom'];
-print ' <a href="deconnexion.php">'.$logout.'</a><br>';
+print ' <a href="deconnexion.php">'.img_picto($langs->trans('Logout'), 'logout.png').'</a><br>';
 print $langs->trans("CashDeskThirdParty").': '.$companyLink.'<br>';
 /*print $langs->trans("CashDeskBankCash").': '.$bankcashLink.'<br>';
 print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'<br>';
diff --git a/htdocs/comm/action/fiche.php b/htdocs/comm/action/fiche.php
index fc671b76436b389a063fe82412303303b20c45ed..ff73c6ee38a4a5aac9d12b5ba4d0182de4c2fc1a 100644
--- a/htdocs/comm/action/fiche.php
+++ b/htdocs/comm/action/fiche.php
@@ -92,14 +92,14 @@ if ($action == 'add_action')
 		exit;
 	}
 
-    $fulldayevent=$_POST["fullday"];
+    $fulldayevent=GETPOST('fullday');
 
     // Clean parameters
 	$datep=dol_mktime($fulldayevent?'00':$_POST["aphour"], $fulldayevent?'00':$_POST["apmin"], 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]);
 	$datef=dol_mktime($fulldayevent?'23':$_POST["p2hour"], $fulldayevent?'59':$_POST["p2min"], $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]);
 
 	// Check parameters
-	if (! $datef && $_POST["percentage"] == 100)
+	if (! $datef && GETPOST('percentage') == 100)
 	{
 		$error++;
 		$action = 'create';
@@ -107,7 +107,7 @@ if ($action == 'add_action')
 	}
 
 	// Initialisation objet cactioncomm
-	if (! $_POST["actioncode"])
+	if (! GETPOST('actioncode'))
 	{
 		$error++;
 		$action = 'create';
@@ -115,14 +115,14 @@ if ($action == 'add_action')
 	}
 	else
 	{
-		$result=$cactioncomm->fetch($_POST["actioncode"]);
+		$result=$cactioncomm->fetch(GETPOST('actioncode'));
 	}
 
 	// Initialisation objet actioncomm
 	$actioncomm->type_id = $cactioncomm->id;
 	$actioncomm->type_code = $cactioncomm->code;
 	$actioncomm->priority = isset($_POST["priority"])?$_POST["priority"]:0;
-	$actioncomm->fulldayevent = $_POST["fullday"]?1:0;
+	$actioncomm->fulldayevent = (! empty($fulldayevent)?1:0);
 	$actioncomm->location = isset($_POST["location"])?$_POST["location"]:'';
 	$actioncomm->label = trim($_POST["label"]);
 	if (! $_POST["label"])
@@ -144,7 +144,7 @@ if ($action == 'add_action')
 	$actioncomm->datep = $datep;
 	$actioncomm->datef = $datef;
 	$actioncomm->percentage = isset($_POST["percentage"])?$_POST["percentage"]:0;
-	$actioncomm->duree=(($_POST["dureehour"] * 60) + $_POST["dureemin"]) * 60;
+	$actioncomm->duree=((GETPOST('dureehour') * 60) + GETPOST('dureemin')) * 60;
 
 	$usertodo=new User($db);
 	if ($_POST["affectedto"] > 0)
@@ -169,8 +169,9 @@ if ($action == 'add_action')
 	}
 
 	// Special for module webcal and phenix
-	if ($_POST["add_webcal"] == 'on' && $conf->webcalendar->enabled) $actioncomm->use_webcal=1;
-	if ($_POST["add_phenix"] == 'on' && $conf->phenix->enabled) $actioncomm->use_phenix=1;
+	// FIXME external modules
+	if (! empty($conf->webcalendar->enabled) && GETPOST('add_webcal') == 'on') $actioncomm->use_webcal=1;
+	if (! empty($conf->phenix->enabled) && GETPOST('add_phenix') == 'on') $actioncomm->use_phenix=1;
 
 	// Check parameters
 	if ($actioncomm->type_code == 'AC_RDV' && ($datep == '' || $datef == ''))
@@ -179,14 +180,14 @@ if ($action == 'add_action')
 		$action = 'create';
 		$mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")).'</div>';
 	}
-	if ($datea && $_POST["percentage"] == 0)
+	if (! empty($datea) && GETPOST('percentage') == 0)
 	{
 		$error++;
 		$action = 'create';
 		$mesg='<div class="error">'.$langs->trans("ErrorStatusCantBeZeroIfStarted").'</div>';
 	}
 
-	if (! $_POST["apyear"] && ! $_POST["adyear"])
+	if (! GETPOST('apyear') && ! GETPOST('adyear'))
 	{
 		$error++;
 		$action = 'create';
@@ -269,23 +270,27 @@ if ($action == 'confirm_delete' && GETPOST("confirm") == 'yes')
  */
 if ($action == 'update')
 {
-	if (! $_POST["cancel"])
+	if (empty($cancel))
 	{
-        $fulldayevent=$_POST["fullday"];
+        $fulldayevent=GETPOST('fullday');
+        $aphour=GETPOST('aphour');
+        $apmin=GETPOST('apmin');
+        $p2hour=GETPOST('p2hour');
+        $p2min=GETPOST('p2min');
 
 	    // Clean parameters
-		if ($_POST["aphour"] == -1) $_POST["aphour"]='0';
-		if ($_POST["apmin"] == -1) $_POST["apmin"]='0';
-		if ($_POST["p2hour"] == -1) $_POST["p2hour"]='0';
-		if ($_POST["p2min"] == -1) $_POST["p2min"]='0';
+		if ($aphour == -1) $aphour='0';
+		if ($apmin == -1) $apmin='0';
+		if ($p2hour == -1) $p2hour='0';
+		if ($p2min == -1) $p2min='0';
 		//if ($_POST["adhour"] == -1) $_POST["adhour"]='0';
 		//if ($_POST["admin"] == -1) $_POST["admin"]='0';
 
 		$actioncomm = new Actioncomm($db);
 		$actioncomm->fetch($id);
 
-		$datep=dol_mktime($fulldayevent?'00':$_POST["aphour"], $fulldayevent?'00':$_POST["apmin"], 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]);
-		$datef=dol_mktime($fulldayevent?'23':$_POST["p2hour"], $fulldayevent?'59':$_POST["p2min"], $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]);
+		$datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]);
+		$datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]);
 
 		$actioncomm->label       = $_POST["label"];
 		$actioncomm->datep       = $datep;
@@ -478,14 +483,14 @@ if ($action == 'create')
 	print '<tr><td width="10%">'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td>';
 	print '<td>';
 	$percent=-1;
-	if (isset($_GET['percentage']) || isset($_POST['percentage']))
+	if (GETPOST('percentage'))
 	{
 		$percent=GETPOST('percentage');
 	}
 	else
 	{
 		if (GETPOST("afaire") == 1) $percent=0;
-		if (GETPOST("afaire") == 2) $percent=100;
+		else if (GETPOST("afaire") == 2) $percent=100;
 	}
 	print $htmlactions->form_select_status_action('formaction',$percent,1,'complete');
 	print '</td></tr>';
@@ -715,7 +720,7 @@ if ($id)
 		print '</td></tr>';
 
 		// Status
-		print '<tr><td nowrap>'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td><td colspan="3">';
+		print '<tr><td nowrap="nowrap">'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td><td colspan="3">';
 		$percent=GETPOST("percentage")?GETPOST("percentage"):$act->percentage;
 		print $htmlactions->form_select_status_action('formaction',$percent,1);
 		print '</td></tr>';
@@ -865,7 +870,7 @@ if ($id)
 		print '</td></tr>';
 
 		// Status
-		print '<tr><td nowrap>'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td><td colspan="2">';
+		print '<tr><td nowrap="nowrap">'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td><td colspan="2">';
 		print $act->getLibStatut(4);
 		print '</td></tr>';
 
diff --git a/htdocs/contrat/fiche.php b/htdocs/contrat/fiche.php
index b098a8d093a6095c2018ba7a864a8addc7ad4f5d..fb4183cfa4de132e80cc9ddcb6b27cf40fa51507 100644
--- a/htdocs/contrat/fiche.php
+++ b/htdocs/contrat/fiche.php
@@ -1358,7 +1358,7 @@ else
                 else print '<a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a>';
             }
 
-            if ($conf->facture->enabled && $object->statut > 0)
+            if ($conf->facture->enabled && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
             {
                 $langs->load("bills");
                 if ($user->rights->facture->creer) print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a>';
diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php
index c3c6475822539280c368415393e53d0e1b844d6a..fc44cc0233275fcf82e9e0eadb91f4c17371ec29 100644
--- a/htdocs/core/class/conf.class.php
+++ b/htdocs/core/class/conf.class.php
@@ -374,6 +374,9 @@ class Conf
         $this->format_date_hour_text_short="%d %b %Y %H:%M";
         $this->format_date_hour_text="%d %B %Y %H:%M";
 
+        // Duration of workday
+        if (! isset($conf->global->MAIN_DURATION_OF_WORKDAY)) $this->global->MAIN_DURATION_OF_WORKDAY=86400;
+
 		// Limites decimales si non definie (peuvent etre egale a 0)
 		if (! isset($this->global->MAIN_MAX_DECIMALS_UNIT))  $this->global->MAIN_MAX_DECIMALS_UNIT=5;
 		if (! isset($this->global->MAIN_MAX_DECIMALS_TOT))   $this->global->MAIN_MAX_DECIMALS_TOT=2;
diff --git a/htdocs/core/class/html.formactions.class.php b/htdocs/core/class/html.formactions.class.php
index 5fa1997d557f2b38dc0f36d93f5bed115a873822..cf63c366792f3d2dc52f579c1f10d48c4aba22b1 100644
--- a/htdocs/core/class/html.formactions.class.php
+++ b/htdocs/core/class/html.formactions.class.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (c) 2008-2012 Laurent Destailleur  <eldy@users.sourceforge.net>
- * Copyright (C) 2010-2011 Regis Houssin        <regis@dolibarr.fr>
+ * Copyright (C) 2010-2012 Regis Houssin        <regis@dolibarr.fr>
  * Copyright (C) 2010      Juanjo Menent        <jmenent@2byte.es>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -58,39 +58,66 @@ class FormActions
     {
         global $langs,$conf;
 
-        $listofstatus=array('-1'=>$langs->trans("ActionNotApplicable"),
-                            '0'=>$langs->trans("ActionRunningNotStarted"),
-                            '50'=>$langs->trans("ActionRunningShort"),
-                            '100'=>$langs->trans("ActionDoneShort"));
+        $listofstatus = array(
+            '-1' => $langs->trans("ActionNotApplicable"),
+            '0' => $langs->trans("ActionRunningNotStarted"),
+            '50' => $langs->trans("ActionRunningShort"),
+            '100' => $langs->trans("ActionDoneShort")
+        );
 
-        if ($conf->use_javascript_ajax)
+        if (! empty($conf->use_javascript_ajax))
         {
             print "\n";
-            print '<script type="text/javascript">'."\n";
-            print 'jQuery(document).ready(function () {'."\n";
-            print 'jQuery("#select'.$htmlname.'").change(function() { select_status(document.'.$formname.'.status.value); });'."\n";
-            print 'jQuery("#val'.$htmlname.'").change(function()    { select_status(document.'.$formname.'.status.value); });'."\n";
-            print 'select_status(document.'.$formname.'.status.value);'."\n";
-            print '});'."\n";
-            print 'function select_status(mypercentage) {'."\n";
-            print 'document.'.$formname.'.percentageshown.value=(mypercentage>=0?mypercentage:\'\');'."\n";
-            print 'document.'.$formname.'.percentage.value=mypercentage;'."\n";
-            print 'if (mypercentage == -1) { document.'.$formname.'.percentageshown.disabled=true; jQuery(".hideifna").hide(); }'."\n";
-            print 'else if (mypercentage == 0) { document.'.$formname.'.percentageshown.disabled=true; jQuery(".hideifna").show();}'."\n";
-            print 'else if (mypercentage == 100) { document.'.$formname.'.percentageshown.disabled=true; jQuery(".hideifna").show();}'."\n";
-            print 'else { document.'.$formname.'.percentageshown.disabled=false; }'."\n";
-            print '}'."\n";
-            print '</script>'."\n";
+            print "<script type=\"text/javascript\">
+                var htmlname = '".$htmlname."';
+
+                $(document).ready(function () {
+                	select_status();
+
+                    $('#select' + htmlname).change(function() {
+                        select_status();
+                    });
+                    // FIXME use another method for update combobox
+                    //$('#val' + htmlname).change(function() {
+                        //select_status();
+                    //});
+                });
+
+                function select_status() {
+                    var defaultvalue = $('#select' + htmlname).val();
+                    var percentage = $('input[name=percentage]');
+                    var selected = '".(isset($selected)?$selected:'')."';
+                    var value = (selected>0?selected:(defaultvalue>=0?defaultvalue:''));
+
+                    percentage.val(value);
+
+                    if (defaultvalue == -1) {
+                        percentage.attr('disabled', 'disabled');
+                        $('.hideifna').hide();
+                    }
+                    else if (defaultvalue == 0) {
+                        percentage.attr('disabled', 'disabled');
+                        $('.hideifna').show();
+                    }
+                    else if (defaultvalue == 100) {
+                        percentage.attr('disabled', 'disabled');
+                        $('.hideifna').show();
+                    }
+                    else {
+                        percentage.removeAttr('disabled');
+                        $('.hideifna').show();
+                    }
+                }
+                </script>\n";
             print '<select '.($canedit?'':'disabled="disabled" ').'name="status" id="select'.$htmlname.'" class="flat">';
             foreach($listofstatus as $key => $val)
             {
-                print '<option value="'.$key.'"'.($selected == $key?' selected="selected"':'').'>'.$val.'</option>';
+                print '<option value="'.$key.'"'.(($selected == $key) || (($selected > 0 && $selected < 100) && $key == '50') ? ' selected="selected"' : '').'>'.$val.'</option>';
             }
             print '</select>';
             if ($selected == 0 || $selected == 100) $canedit=0;
-            print ' <input type="text" id="val'.$htmlname.'" name="percentageshown" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled="disabled"').'>';
+            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled="disabled"').'>';
             print '<span class="hideifna">%</span>';
-            print ' <input type="hidden" name="percentage" value="'.$selected.'">';
         }
         else
         {
diff --git a/htdocs/core/datepicker.php b/htdocs/core/datepicker.php
index 4db6de685ace9116295106af84a4e00568da8578..daf63f06d19abe943a5a0c2e255a7a6caf8e1c94 100644
--- a/htdocs/core/datepicker.php
+++ b/htdocs/core/datepicker.php
@@ -232,8 +232,8 @@ function displayBox($selectedDate,$month,$year)
 
 		// Sur click dans calendrier, appelle fonction dpClickDay
 		echo "<TD class=\"".$dayclass."\"";
-		echo " onMouseOver=\"dpHighlightDay(".$mydate["year"].",".dol_print_date($thedate,"%m").",".$mydate["mday"].",tradMonths)\"";
-		echo " onClick=\"dpClickDay(".$mydate["year"].",".dol_print_date($thedate,"%m").",".$mydate["mday"].",'".$langs->trans("FormatDateShortJava")."')\"";
+		echo " onMouseOver=\"dpHighlightDay(".$mydate["year"].",parseInt('".dol_print_date($thedate,"%m")."',10),".$mydate["mday"].",tradMonths)\"";
+		echo " onClick=\"dpClickDay(".$mydate["year"].",parseInt('".dol_print_date($thedate,"%m")."',10),".$mydate["mday"].",'".$langs->trans("FormatDateShortJava")."')\"";
 		echo ">".sprintf("%02s",$mydate["mday"])."</TD>";
 		$cols++;
 
@@ -278,4 +278,4 @@ function displayBox($selectedDate,$month,$year)
 		<?php
 }//end function
 
-?>
\ No newline at end of file
+?>
diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php
index 96776c1af1dca712612b3876796d6ee90723b1f9..9915cc703d64ce97947468304b71ea06ec7db0a3 100644
--- a/htdocs/core/lib/files.lib.php
+++ b/htdocs/core/lib/files.lib.php
@@ -790,16 +790,17 @@ function dol_delete_dir_recursive($dir,$count=0,$nophperrors=0)
 function dol_delete_preview($object)
 {
 	global $langs,$conf;
-    require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
 
     $element = $object->element;
-    $dir = $conf->$element->dir_output;
 
-    if ($object->element == 'order_supplier')   $dir = $conf->fournisseur->dir_output.'/commande';
-    elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture';
-    elseif ($object->element == 'project')          $dir = $conf->projet->dir_output;
-    elseif ($object->element == 'shipping')         $dir = $conf->expedition->dir_output.'/sending';
-    elseif ($object->element == 'delivery')         $dir = $conf->expedition->dir_output.'/receipt';
+    if ($object->element == 'order_supplier')		$dir = $conf->fournisseur->dir_output.'/commande';
+    elseif ($object->element == 'invoice_supplier')	$dir = $conf->fournisseur->dir_output.'/facture';
+    elseif ($object->element == 'project')			$dir = $conf->projet->dir_output;
+    elseif ($object->element == 'shipping')			$dir = $conf->expedition->dir_output.'/sending';
+    elseif ($object->element == 'delivery')			$dir = $conf->expedition->dir_output.'/receipt';
+    elseif ($object->element == 'fichinter')		$dir = $conf->ficheinter->dir_output;
+    else
+    	$dir = $conf->$element->dir_output;
 
     if (empty($dir)) return 'ErrorObjectNoSupportedByFunction';
 
diff --git a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
index d36b371799aa48eaa391939824d0617f2fd9c027..062acb79557b7d672189e9e17a143575b0608827 100644
--- a/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
+++ b/htdocs/core/modules/fichinter/doc/pdf_soleil.modules.php
@@ -86,7 +86,8 @@ class pdf_soleil extends ModelePDFFicheinter
 
 		// Recupere emmetteur
 		$this->emetteur=$mysoc;
-		if (! $this->emetteur->code_pays) $this->emetteur->code_pays=substr($langs->defaultlang,-2);    // By default, if not defined
+		if (empty($this->emetteur->country_code))
+			$this->emetteur->country_code = substr($langs->defaultlang,-2);    // By default, if not defined
 
 		// Defini position des colonnes
 		$this->posxdesc=$this->marge_gauche+1;
@@ -271,6 +272,7 @@ class pdf_soleil extends ModelePDFFicheinter
 						$nexY+=2;    // Passe espace entre les lignes
 
 						// Detect if some page were added automatically and output _tableau for past pages
+						// FIXME $pageposafter not defined
 						while ($pagenb < $pageposafter)
 						{
 							if ($pagenb == 1)
@@ -553,7 +555,7 @@ class pdf_soleil extends ModelePDFFicheinter
 				$carac_client_name=$outputlangs->convToOutputCharset($object->client->nom);
 			}
 
-			$carac_client=pdf_build_address($outputlangs,$this->emetteur,$object->client,$object->contact,$usecontact,'target');
+			$carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->client, (isset($object->contact)?$object->contact:''), $usecontact, 'target');
 
 			// Show recipient
 			$posy=42;
diff --git a/htdocs/core/modules/fichinter/modules_fichinter.php b/htdocs/core/modules/fichinter/modules_fichinter.php
index edd5be4401a5e2dabfa3c7582524dcb2473c1797..0b06b7132ffbe18503d7cfeab91e671f610cfcc1 100644
--- a/htdocs/core/modules/fichinter/modules_fichinter.php
+++ b/htdocs/core/modules/fichinter/modules_fichinter.php
@@ -44,7 +44,7 @@ abstract class ModelePDFFicheinter extends CommonDocGenerator
      *  @param  string	$maxfilenamelength  Max length of value to show
      *  @return	array						List of templates
 	 */
-	function liste_modeles($db,$maxfilenamelength=0)
+	static function liste_modeles($db,$maxfilenamelength=0)
 	{
 		global $conf;
 
@@ -224,9 +224,6 @@ function fichinter_create($db, $object, $modele, $outputlangs, $hidedetails=0, $
 			require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
 			dol_delete_preview($object);
 
-			// Success in building document. We build meta file.
-			dol_meta_create($object);
-
 			// Appel des triggers
 			include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
 			$interface=new Interfaces($db);
diff --git a/htdocs/core/modules/societe/mod_codecompta_aquarium.php b/htdocs/core/modules/societe/mod_codecompta_aquarium.php
index 7fb6ca02cbaba2dc15d5d8f5c6b42fbf6e7271b6..e0e7faa530e1abc8c14499addf8b162f46d8d1c2 100644
--- a/htdocs/core/modules/societe/mod_codecompta_aquarium.php
+++ b/htdocs/core/modules/societe/mod_codecompta_aquarium.php
@@ -113,10 +113,16 @@ class mod_codecompta_aquarium extends ModeleAccountancyCode
 
 		// Regle gestion compte compta
 		$codetouse='';
-		if ($type == 'customer') $codetouse = $this->prefixcustomeraccountancycode;
-		if ($type == 'supplier') $codetouse = $this->prefixsupplieraccountancycode;
-		if ($type == 'customer') $codetouse.= (! empty($societe->code_client)?$societe->code_client:'CUSTCODE');
-		if ($type == 'supplier') $codetouse.= (! empty($societe->code_fournisseur)?$societe->code_fournisseur:'SUPPCODE');
+		if ($type == 'customer')
+		{
+			$codetouse = $this->prefixcustomeraccountancycode;
+			$codetouse.= (! empty($societe->code_client)?$societe->code_client:'CUSTCODE');
+		}
+		else if ($type == 'supplier')
+		{
+			$codetouse = $this->prefixsupplieraccountancycode;
+			$codetouse.= (! empty($societe->code_fournisseur)?$societe->code_fournisseur:'SUPPCODE');
+		}
 		$codetouse=strtoupper(preg_replace('/([^a-z0-9])/i','',$codetouse));
 
 		$is_dispo = $this->verif($db, $codetouse, $societe, $type);
@@ -147,11 +153,11 @@ class mod_codecompta_aquarium extends ModeleAccountancyCode
 	{
 		$sql = "SELECT ";
 		if ($type == 'customer') $sql.= "code_compta";
-		if ($type == 'supplier') $sql.= "code_compta_fournisseur";
+		else if ($type == 'supplier') $sql.= "code_compta_fournisseur";
 		$sql.= " FROM ".MAIN_DB_PREFIX."societe";
 		$sql.= " WHERE ";
 		if ($type == 'customer') $sql.= "code_compta";
-		if ($type == 'supplier') $sql.= "code_compta_fournisseur";
+		else if ($type == 'supplier') $sql.= "code_compta_fournisseur";
 		$sql.= " = '".$this->db->escape($code)."'";
 		if (! empty($societe->id)) $sql.= " AND rowid <> ".$societe->id;
 
diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php
index d2287050cc4eea121c718b8805157fdbec4d80b3..0498ab21466d1106242eb1a4b6aa7a5af06b53b3 100644
--- a/htdocs/fichinter/class/fichinter.class.php
+++ b/htdocs/fichinter/class/fichinter.class.php
@@ -87,7 +87,7 @@ class Fichinter extends CommonObject
 	 */
 	function create()
 	{
-		global $conf;
+		global $conf, $user, $langs;
 
 		dol_syslog(get_class($this)."::create ref=".$this->ref);
 
@@ -156,8 +156,8 @@ class Fichinter extends CommonObject
 		$result=$this->db->query($sql);
 		if ($result)
 		{
-                        $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."fichinter");
-                        $this->db->commit();
+			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."fichinter");
+			$this->db->commit();
 
 			// Appel des triggers
 			include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
@@ -328,10 +328,9 @@ class Fichinter extends CommonObject
 	 *	Validate a intervention
 	 *
 	 *	@param		User		$user		User that validate
-	 *	@param		string		$outputdir	Output directory
 	 *	@return		int			<0 if KO, >0 if OK
 	 */
-	function setValid($user, $outputdir)
+	function setValid($user)
 	{
 		global $langs, $conf;
 
diff --git a/htdocs/fichinter/fiche.php b/htdocs/fichinter/fiche.php
index 8c7eb21e1f89a046141c2b244c19980cda6a041c..34edbbc26758740ef31a5032d8de19e208cdb1e1 100644
--- a/htdocs/fichinter/fiche.php
+++ b/htdocs/fichinter/fiche.php
@@ -76,7 +76,7 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->fichein
     $object->fetch($id);
     $object->fetch_thirdparty();
 
-    $result = $object->setValid($user, $conf->fichinter->outputdir);
+    $result = $object->setValid($user);
     if ($result >= 0)
     {
         // Define output language
@@ -905,7 +905,7 @@ else if ($id > 0 || ! empty($ref))
 
     // Duration
     print '<tr><td>'.$langs->trans("TotalDuration").'</td>';
-    print '<td>'.convertSecondToTime($object->duree,'all',$conf->global->MAIN_DURATION_OF_WORKDAY).'</td>';
+    print '<td>'.convertSecondToTime($object->duree, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>';
     print '</tr>';
 
     // Description (must be a textarea and not html must be allowed (used in list view)
diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php
index dfced7618f51451f65b4e9d96a0a32dd38193b78..62a146fa289e06d570b797c3e4f08a41b691f366 100755
--- a/htdocs/fichinter/list.php
+++ b/htdocs/fichinter/list.php
@@ -42,21 +42,12 @@ $result = restrictedArea($user, 'ficheinter', $fichinterid,'fichinter');
 $sortfield = GETPOST('sortfield','alpha');
 $sortorder = GETPOST('sortorder','alpha');
 $page = GETPOST('page','int');
-if ($page == -1) {
-	$page = 0;
-}
+if ($page == -1) { $page = 0; }
 $offset = $conf->liste_limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-
 if (! $sortorder) $sortorder="DESC";
 if (! $sortfield) $sortfield="fd.date";
-if ($page == -1) { $page = 0 ; }
-
-$limit = $conf->liste_limit;
-$offset = $limit * $page ;
-$pageprev = $page - 1;
-$pagenext = $page + 1;
 
 $search_ref=GETPOST('search_ref','alpha');
 $search_company=GETPOST('search_company','alpha');
diff --git a/htdocs/fichinter/rapport.php b/htdocs/fichinter/rapport.php
index 890b0e4bfbe924f45ce1610e7adc0f2d4b43c3d6..0be18134f70c970412945d9ff2014d323745109c 100644
--- a/htdocs/fichinter/rapport.php
+++ b/htdocs/fichinter/rapport.php
@@ -23,9 +23,23 @@ require_once(DOL_DOCUMENT_ROOT."/contact/class/contact.class.php");
 
 $langs->load("interventions");
 
+$socid=GETPOST('socid', 'int');
+
 // Security check
-if ($user->societe_id) $socid=$user->societe_id;
-$result = restrictedArea($user, 'ficheinter', $fichinterid, 'fichinter');
+if (! empty($user->societe_id))	$socid=$user->societe_id;
+$result = restrictedArea($user, 'ficheinter', '', 'fichinter');
+
+$sortfield = GETPOST('sortfield','alpha');
+$sortorder = GETPOST('sortorder','alpha');
+$page = GETPOST('page','int');
+if ($page == -1) {
+	$page = 0;
+}
+$offset = $conf->liste_limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (! $sortorder) $sortorder="ASC";
+if (! $sortfield) $sortfield="f.datei";
 
 
 /*
@@ -34,21 +48,7 @@ $result = restrictedArea($user, 'ficheinter', $fichinterid, 'fichinter');
 
 llxHeader();
 
-if ($sortorder == "")
-{
-	$sortorder="ASC";
-}
-if ($sortfield == "")
-{
-	$sortfield="f.datei";
-}
-
-if ($page == -1) { $page = 0 ; }
-
-$limit = $conf->liste_limit;
-$offset = $limit * $page ;
-$pageprev = $page - 1;
-$pagenext = $page + 1;
+$now=dol_now();
 
 $sql = "SELECT s.nom, s.rowid as socid, f.description, f.ref";
 $sql.= ", f.datei as dp, f.rowid as fichid, f.fk_statut, f.duree";
@@ -56,23 +56,22 @@ $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
 $sql.= ", ".MAIN_DB_PREFIX."fichinter as f ";
 $sql.= " WHERE f.fk_soc = s.rowid";
 $sql.= " AND f.entity = ".$conf->entity;
-
-
-if ($socid > 0)
-{
+if (! empty($socid))
 	$sql .= " AND s.rowid = " . $socid;
-}
 
-if (empty ($MM))
-$MM=strftime("%m",time());
+
+if (empty($MM))
+	$MM=strftime("%m", $now);
 if (empty($YY))
-$YY=strftime("%Y",time());;
+	$YY=strftime("%Y", $now);
+
 echo "<div class='noprint'>";
-echo "\n<form action='rapport.php'>";
+echo '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
+echo '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 echo "<input type='hidden' name='socid' value='".$socid."'>";
 echo $langs->trans("Month")." <input name='MM' size='2' value='$MM'>";
 echo " Ann&eacute;e <input size='4' name='YY' value='$YY'>";
-echo "<input type='submit' name='g' value='G&eacute;n&eacute;rer le rapport'>";
+echo "<input type='submit' name='action' value='generate' />";
 echo "<form>";
 echo "</div>";
 
@@ -100,7 +99,7 @@ if ($resql)
 
 	$i = 0;
 	print '<table class="noborder" width="100%" cellspacing="0" cellpadding="3">';
-	print "<tr class=\"liste_titre\">";
+	print '<tr class="liste_titre">';
 	print '<td>Num</td>';
 	if (empty($socid))
 	print '<td>'.$langs->trans("Customers").'</td>';
@@ -120,9 +119,9 @@ if ($resql)
 
 		if (empty($socid))
 		{
-			if (!empty($MM)) $filter="&MM=$MM&YY=$YY";
-			print '<td><a href="rapport.php?socid='.$objp->socid.$filter.'"><img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/filter.png" border="0"></a>&nbsp;';
-			print "<a href=\"".DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->rowid.$filter."\">".$objp->nom."</a></TD>\n";
+			if (!empty($MM)) $filter='&MM='.$MM.'&YY='.$YY;
+			print '<td><a href="'.$_SERVER['PHP_SELF'].'?socid='.$objp->socid.$filter.'"><img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/filter.png" border="0"></a>&nbsp;';
+			print '<a href="'.DOL_URL_ROOT.'/comm/fiche.php?socid='.$objp->rowid.$filter.'">'.$objp->nom.'</a></td>'."\n";
 		}
 		print '<td>'.nl2br($objp->description).'</td>';
 		print "<td>".dol_print_date($db->jdate($objp->dp),"day")."</td>\n";
@@ -140,7 +139,8 @@ else
 {
 	dol_print_error($db);
 }
-$db->close();
+
 
 llxFooter();
+$db->close();
 ?>
diff --git a/htdocs/install/mysql/data/llx_const.sql b/htdocs/install/mysql/data/llx_const.sql
index 3b805222b4bbc53c55e7ad25d671433384c8cf01..23b20a0411bbbcdb1b44ff39f814cf3c573bbdba 100644
--- a/htdocs/install/mysql/data/llx_const.sql
+++ b/htdocs/install/mysql/data/llx_const.sql
@@ -35,6 +35,7 @@ insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_N
 insert into llx_const (name, value, type, note, visible, entity) values ('MAIN_FEATURES_LEVEL','0','chaine','Level of features to show (0=stable only, 1=stable+experimental, 2=stable+experimental+development',1,0);
 
 -- Hidden and common to all entities
+insert into llx_const (name, value, type, note, visible, entity) values ('SYSLOG_FILE_ON','1','chaine','Log to file Directory where to write log file',0,0);
 insert into llx_const (name, value, type, note, visible, entity) values ('SYSLOG_FILE','DOL_DATA_ROOT/dolibarr.log','chaine','Directory where to write log file',0,0);
 insert into llx_const (name, value, type, note, visible, entity) values ('SYSLOG_LEVEL','7','chaine','Level of debug info to show',0,0);
 
diff --git a/htdocs/install/mysql/migration/3.1.0-3.2.0.sql b/htdocs/install/mysql/migration/3.1.0-3.2.0.sql
index bb5d9f98fc30b7c22d72fd3c2f298abfbb594f51..39d346c1de2f8237affb1dacddf7aa5d52fe747a 100755
--- a/htdocs/install/mysql/migration/3.1.0-3.2.0.sql
+++ b/htdocs/install/mysql/migration/3.1.0-3.2.0.sql
@@ -458,3 +458,5 @@ ALTER TABLE llx_product_fournisseur_price MODIFY fk_product_fournisseur integer
 UPDATE llx_product SET canvas = NULL where canvas = 'default@product';
 UPDATE llx_product SET canvas = NULL where canvas = 'product@product';
 UPDATE llx_product SET canvas = NULL where canvas = 'service@product';
+
+DELETE FROM llx_const WHERE __DECRYPT('name')__ = 'SOCIETE_CODECOMPTA_ADDON' AND __DECRYPT('value')__ = 'mod_codecompta_digitaria';
diff --git a/htdocs/langs/ca_ES/dict.lang b/htdocs/langs/ca_ES/dict.lang
index e8f6656fd710e3adff19eb767bd5f0260e69c217..0b3ad8ca7bbb250b61636aab5d93eca010f66d04 100644
--- a/htdocs/langs/ca_ES/dict.lang
+++ b/htdocs/langs/ca_ES/dict.lang
@@ -246,12 +246,13 @@ CountryJE=Jersey
 CountryME=Monténégro
 CountryBL=Saint-Barthélemy
 CountryMF=Saint-Martin
-##### Civilities #####
+##### Civilities #####=undefined
 CivilityMME=Senyora
 CivilityMR=Senyor
 CivilityMLE=Senyoreta
 CivilityMTRE=En
-##### Currencies #####
+CivilityDR=Doctor
+##### Currencies #####=undefined
 Currencyeuros=Euros
 CurrencyAUD=Dòlars Aus.
 CurrencySingAUD=Dòlar Aus.
@@ -293,11 +294,35 @@ CurrencyXPF=Francs CFP
 CurrencySingXPF=Franc CFP
 CurrencyCentSingEUR=cèntim
 CurrencyThousandthSingTND=mil·lèsim
-#### Input reasons #####
+#### Input reasons ####=
 DemandReasonTypeSRC_INTE=Internet
 DemandReasonTypeSRC_CAMP_MAIL=Campanya correu
 DemandReasonTypeSRC_CAMP_EMAIL=Campanya E-Mailing
 DemandReasonTypeSRC_CAMP_PHO=Campanya telefònica
 DemandReasonTypeSRC_CAMP_FAX=Campanya fax
 DemandReasonTypeSRC_COMM=Contacte comercial
-DemandReasonTypeSRC_SHOP=Contacte botiga
\ No newline at end of file
+DemandReasonTypeSRC_SHOP=Contacte botiga
+DemandReasonTypeSRC_WOM=Boca a boca
+DemandReasonTypeSRC_PARTNER=Soci
+DemandReasonTypeSRC_EMPLOYEE=Empleat
+DemandReasonTypeSRC_SPONSORSHIP=Patrocinador
+#### Paper formats ####=
+PaperFormatEU4A0=Format 4A0
+PaperFormatEU2A0=Format 2A0
+PaperFormatEUA0=Format A0
+PaperFormatEUA1=Format A1
+PaperFormatEUA2=Format A2
+PaperFormatEUA3=Format A3
+PaperFormatEUA4=Format A4
+PaperFormatEUA5=Format A5
+PaperFormatEUA6=Format A6
+PaperFormatUSLETTER=Format carta EE. UU.
+PaperFormatUSLEGAL=
+PaperFormatUSEXECUTIVE=Format executiu EE. UU.
+PaperFormatUSLEDGER=Format tabloide
+PaperFormatCAP1=Format canadec P1
+PaperFormatCAP2=Format canadec P2
+PaperFormatCAP3=Format canadec P3
+PaperFormatCAP4=Format canadec P4
+PaperFormatCAP5=Format canadec P5
+PaperFormatCAP6=Format canadec P6
diff --git a/htdocs/langs/ca_ES/errors.lang b/htdocs/langs/ca_ES/errors.lang
index 44668eddf64ae65fbfb95a8f0fb8818707826f23..b5c8696a08d34f34fc48418dc01b532421ab39c1 100644
--- a/htdocs/langs/ca_ES/errors.lang
+++ b/htdocs/langs/ca_ES/errors.lang
@@ -1,7 +1,7 @@
-# Dolibarr language file - ca_ES - errors
+# Dolibarr language file - ca_ES - errors 
 CHARSET=UTF-8
 MenuManager=Gestor de menú
-# Errors
+# Errors=
 Error=Error
 Errors=Errors
 ErrorBadEMail=e-mail %s incorrecte
@@ -102,15 +102,14 @@ ErrorLoginDoesNotExists=El compte d'usuari de <b>%s</b> no s'ha trobat.
 ErrorLoginHasNoEmail=Aquest usuari no té e-mail. Impossible continuar.
 ErrorBadValueForCode=Valor no vàlid per al codi. Torneu a intentar-ho amb un nou valor ...
 ErrorBothFieldCantBeNegative=Els camps %s i %s no poden ser negatius
-ErrorNoActivatedBarcode=Cap tipus de codi de barres activat
-ErrorWebServerUserHasNotPermission=El compte d'execució del servidor web <b>%s</b> no disposa dels permisos per això
 ErrorNoActivatedBarcode=No hi ha activat cap tipus de codi de barres
+ErrorWebServerUserHasNotPermission=El compte d'execució del servidor web <b>%s</b> no disposa dels permisos per això
 ErrUnzipFails=No s'ha pogut descomprimir el fitxer %s amb ZipArchive
 ErrNoZipEngine=En aquest PHP no hi ha motor per descomprimir l'arxiu %s
 ErrorFileMustBeADolibarrPackage=El fitxer %s ha de ser un paquet Dolibarr en format zip
 ErrorFileRequired=Es requereix un fitxer de paquet Dolibarr en format zip
 ErrorPhpCurlNotInstalled=L'extensió PHP CURL no es troba instal·lada, és indispensable per dialogar amb Paypal.
-
+ErrorFailedToAddToMailmanList=S'ha produït un error en intentar afegir un registre a la llista Mailman o base de dades SPIP
 # Warnings
 WarningSafeModeOnCheckExecDir=Atenció, està activada l'opció PHP <b>safe_mode</b>, la comanda ha d'estar dins d'un directori declarat dins del paràmetre php <b>safe_mode_exec_dir</b>.
 WarningAllowUrlFopenMustBeOn=El paràmetre <b>allow_url_fopen</b> ha de ser especificat a <b>on</b> a l'arxiu <b>php.ini</b> per disposar d'aquest mòdul completament actiu. Ha de modificar aquest arxiu manualment
@@ -121,4 +120,5 @@ WarningConfFileMustBeReadOnly=Atenció, el seu fitxer (<b>htdocs/conf/conf.php</
 WarningsOnXLines=Alertes a <b>%s</b> línies font
 WarningNoDocumentModelActivated=No hi ha cap model per a la generació del document activat. Es prendrà un model per defecte fins que es configuri el mòdul.
 WarningLockFileDoesNotExists=Atenció: Un cop acabada l'instal·lació, han de desactivar les eines d'instal·lació/actualització afegint l'arxiu <b>install.lock</b> al directori <b>%s</b>. L'absència d'aquest imatge mostra una fallada de seguretat.
-WarningUntilDirRemoved=Aquesta alerta seguirà activa mentre la carpeta existeixi (alerta visible per als usuaris admin solament).
\ No newline at end of file
+WarningUntilDirRemoved=Aquesta alerta seguirà activa mentre la carpeta existeixi (alerta visible per als usuaris admin solament).
+WarningCloseAlways=Avís, el tancament és realitzat encara que la quantitat total difereixi entre els elements d'origen i destí. Activi aquesta funcionalitat amb precaució.
diff --git a/htdocs/langs/ca_ES/exports.lang b/htdocs/langs/ca_ES/exports.lang
index b344a4652b2d2c954b7e0458dbb83ce71173fda7..dc5bdc0a2a12e38da134787cf0e7d5441d4af6ba 100644
--- a/htdocs/langs/ca_ES/exports.lang
+++ b/htdocs/langs/ca_ES/exports.lang
@@ -112,4 +112,7 @@ SourceExample=Exemple de dades d'origen possibles
 ExampleAnyRefFoundIntoElement=Totes les referències trobades per als elements <b>%s</b>
 ExampleAnyCodeOrIdFoundIntoDictionnary=Tots els codis (o id) trobats en el diccionari <b>%s</b>
 CSVFormatDesc=Arxiu amb format <b>Valors separats per coma</b> (.csv).<br>És un fitxer amb format de text en què els camps són separats pel caràcter [ %s ]. Si el separador es troba en el contingut d'un camp, el camp ha d'estar tancat per el caràcter [ %s ]. El caràcter d'escapament per a incloure un caràcter d'entorn en una dada és [ %s ].
-ExportFieldAutomaticallyAdded=S'ha afegit automàticament el camp <b>%s</b>, ja que evitarà que línies idèntiques siguin considerades com duplicades (amb aquest camp, cada línia tindrà un id propi).
\ No newline at end of file
+Excel95FormatDesc=Arxiu amb format <b>Excel</b> (.xls)<br>Aquest és el format natiu d'Excel 95 (BIFF5).
+Excel2007FormatDesc=Arxiu amb format <b>Excel</b> (.xlsx)<br>Aquest és el format natiu d'Excel 2007 (SpreadsheetML).
+TsvFormatDesc=Arxiu amb format <b>Valors separats per tabulador</b> (. Tsv)<br> Aquest és un format d'arxiu de text en què els camps són separats per un tabulador [tab].
+ExportFieldAutomaticallyAdded=S'ha afegit automàticament el camp <b>%s</b>, ja que evitarà que línies idèntiques siguin considerades com duplicades (amb aquest camp, cada línia tindrà un id propi).
diff --git a/htdocs/langs/ca_ES/interventions.lang b/htdocs/langs/ca_ES/interventions.lang
index 6e88b27bddd36c62222919c7eac407317cfc7ebc..01d4027d7f695a2f3a98ac30703a6c1d22153005 100644
--- a/htdocs/langs/ca_ES/interventions.lang
+++ b/htdocs/langs/ca_ES/interventions.lang
@@ -1,4 +1,4 @@
-# Dolibarr language file - ca_ES - interventions
+# Dolibarr language file - ca_ES - interventions 
 CHARSET=UTF-8
 Intervention=Intervenció
 Interventions=Intervencions
@@ -23,6 +23,7 @@ ConfirmModifyIntervention=Esteu segur de voler modificar aquesta intervenció?
 ConfirmDeleteInterventionLine=Esteu segur de voler eliminar aquesta línia?
 NameAndSignatureOfInternalContact=Nom i signatura del participant:
 NameAndSignatureOfExternalContact=Nom i signatura del client:
+DocumentModelStandard=Document model estàndard per a intervencions
 InterventionCardsAndInterventionLines=Fitxes i línies d'intervenció
 InterId=Id intervenció
 InterRef=Ref. intervenció
@@ -39,15 +40,15 @@ ClassifyBilled=Classificar "Facturado"
 StatusInterInvoiced=Facturado
 RelatedInterventions=Intervencions adjuntes
 ShowIntervention=Mostrar intervenció
-##### Types de contacts #####
+##### Types de contacts #####=undefined
 TypeContact_fichinter_internal_INTERREPFOLL=Responsable seguiment de la intervenció
 TypeContact_fichinter_internal_INTERVENING=Interventor
 TypeContact_fichinter_external_BILLING=Contacte client facturació intevenció
 TypeContact_fichinter_external_CUSTOMER=Contacte client seguiment intervenció
-# Modele numérotation
+# Modele numérotation=undefined
 ArcticNumRefModelDesc1=Model de numeració genèric
 ArcticNumRefModelError=Activació impossible
 PacificNumRefModelDesc1=Retorna el número amb el format %syymm-nnnn on yy és l'any, mm. el mes i nnnn un comptador seqüencial sense ruptura i sense quedar a 0
 PacificNumRefModelError=Una factura que comença per # $$syymm existeix en base i és incompatible amb aquesta numeració. Elemínela o renombrela per activar aquest mòdul.
 SendInterventionByMail=Enviament fitxa d'intervenció per correu
-SendInterventionRef=Enviament intervenció %s
\ No newline at end of file
+SendInterventionRef=Enviament intervenció %s
diff --git a/htdocs/langs/ca_ES/mails.lang b/htdocs/langs/ca_ES/mails.lang
index 24a5be04af4777ac1f4f050432ca7f3766a09374..3e924788ed072341c8f23e8b1a3daade86c73e8f 100644
--- a/htdocs/langs/ca_ES/mails.lang
+++ b/htdocs/langs/ca_ES/mails.lang
@@ -1,4 +1,4 @@
-# Dolibarr language file - ca_ES - mails
+# Dolibarr language file - ca_ES - mails 
 CHARSET=UTF-8
 Mailing=E-Mailing
 EMailing=E-Mailing
@@ -39,12 +39,13 @@ MailingStatusDraft=Esborrany
 MailingStatusValidated=Validat
 MailingStatusApproved=Aprovat
 MailingStatusSent=Enviat
-MailingStatusRead=Llegit
 MailingStatusSentPartialy=Enviat parcialment
 MailingStatusSentCompletely=Enviat completament
 MailingStatusError=Error
 MailingStatusNotSent=No enviat
 MailSuccessfulySent=E-mail enviat correctament (de %s a %s)
+MailUnsubcribe=Desubscriure
+Unsuscribe=Desubscriure
 ErrorMailRecipientIsEmpty=L'adreça del destinatari és buida
 WarningNoEMailsAdded=Cap nou e-mail a afegir a la llista destinataris.
 ConfirmValidMailing=Confirmeu la validació del E-Mailing?
@@ -70,6 +71,12 @@ CloneReceivers=Clonar destinataris
 DateLastSend=Data últim enviament
 DateSending=Data enviament
 SentTo=Enviat a <b>%s</b>
+MailingStatusRead=Llegit
+CheckRead=Confirmació de lectura
+YourMailUnsubcribeOK=El correu electrònic <b>%s</b>  és correcta desuscribe.
+MailtoEMail=mailto email (hyperlink)
+ActivateCheckRead=Activar confirmació de lectura i opció de Desubscripció
+ActivateCheckReadKey=Clau usada per xifrar la URL de la confirmació de lectura i la funció de desubscripció
 # Libelle des modules de liste de destinataires mailing==
 MailingModuleDescContactCompanies=Contactes de tercers (clients potencials, clients, proveïdors ...)
 MailingModuleDescDolibarrUsers=Usuaris de Dolibarr
@@ -110,4 +117,4 @@ ANotificationsWillBeSent=1 notificació serà enviada per e-mail
 SomeNotificationsWillBeSent=%s notificacions seran enviades per e-mail
 AddNewNotification=Activar una nova sol·licitud de notificació
 ListOfActiveNotifications=Llista de les sol·licituds de notificacions actives
-ListOfNotificationsDone=Llista de notificacions d'e-mails enviades
\ No newline at end of file
+ListOfNotificationsDone=Llista de notificacions d'e-mails enviades
diff --git a/htdocs/langs/ca_ES/main.lang b/htdocs/langs/ca_ES/main.lang
index 3a894bc754b30854507e36f88511d9f418642f3f..b6f9a7e149442bd07d458a3ad4be8d20c4bdcd30 100644
--- a/htdocs/langs/ca_ES/main.lang
+++ b/htdocs/langs/ca_ES/main.lang
@@ -1,4 +1,4 @@
-# Dolibarr language file - ca_ES - main
+# Dolibarr language file - ca_ES - main 
 CHARSET=UTF-8
 DIRECTION=ltr
 SeparatorDecimal=,
@@ -132,6 +132,7 @@ ToClone=Copiar
 ConfirmClone=Seleccions dades que voleu copiar.
 NoCloneOptionsSpecified=no hi ha dades definits per copiar
 Of=de
+Go=Anar
 CopyOf=Còpia de
 Show=Veure
 ShowCardHere=Veure la fitxa aquí
@@ -623,7 +624,6 @@ BySalesRepresentative=Per comercial
 LinkedToSpecificUsers=Enllaçat a un contacte d'usuari particular
 DeleteAFile=Eliminació d'arxiu
 ConfirmDeleteAFile=Confirma l'eliminació de l'arxiu
-
 # Week day
 Monday=Dilluns
 Tuesday=Dimarts
@@ -653,3 +653,6 @@ ShortThursday=Dj
 ShortFriday=Dv
 ShortSaturday=Ds
 ShortSunday=Dg
+View=Veure
+Test=Prova
+Element=Element
diff --git a/htdocs/langs/ca_ES/members.lang b/htdocs/langs/ca_ES/members.lang
index 0b42727353a6811d791108be8ba630be3308d9d6..84559d8dcb24452474f3b4df1351ffa86d06fcf0 100644
--- a/htdocs/langs/ca_ES/members.lang
+++ b/htdocs/langs/ca_ES/members.lang
@@ -1,4 +1,4 @@
-# Dolibarr language file - ca_ES - members
+# Dolibarr language file - ca_ES - members 
 CHARSET=UTF-8
 MembersArea=Àrea membres
 PublicMembersArea=Àrea pública dels membres
@@ -144,12 +144,12 @@ DescADHERENT_MAIL_RESIL_SUBJECT=Assumpte d'e-mail de baixa
 DescADHERENT_MAIL_RESIL=E-mail de baixa
 DescADHERENT_MAIL_FROM=E-mail emissor per als e-mails automàtics
 DescADHERENT_ETIQUETTE_TYPE=Format pàgines etiquetes
+DescADHERENT_ETIQUETTE_TEXT=Text a imprimir a la direcció de les etiquetes de cada membre
 DescADHERENT_CARD_TYPE=Format pàgines carnet de membre
 DescADHERENT_CARD_HEADER_TEXT=Text a imprimir en la part superior del carnet de membre
 DescADHERENT_CARD_TEXT=Text a imprimir en el carnet de membre (Alineat a la dreta)
 DescADHERENT_CARD_TEXT_RIGHT=Text a imprimir en el carnet de membre (Alineat a la dreta)
 DescADHERENT_CARD_FOOTER_TEXT=Text a imprimir a la part inferior del carnet de membre
-DescADHERENT_MAILMAN_LISTS=Llista(s) per a la inscripció automàtica dels nous membres (separats per comes)
 GlobalConfigUsedIfNotDefined=S'utilitzarà el text definit en la configuració del mòdul Membres si no es defineix aquí
 MayBeOverwrited=Aquest valor pot ser sobreescrit pel text definit en el tipus de membre
 ShowTypeCard=Veure tipus '%s'
@@ -196,4 +196,4 @@ Associations=Asssociacions
 Collectivités=Col.lectivitats
 Particuliers=Particulars
 Entreprises=Empreses
-DOLIBARRFOUNDATION_PAYMENT_FORM=Per realitzar el pagament de la seva cotització per transferència bancària, visiteu la pàgina <a target="_blank" href="http://wiki.dolibarr.org/index.php/Subscribirse#Para_una_adhesi.C3.B3n_por_transferencia">http://wiki.dolibarr.org/index.php/Subscribirse</a>.<br>Per pagar amb targeta de crèdit o PayPal, feu clic al botó a la part inferior d'aquesta pàgina.<br><br>
\ No newline at end of file
+DOLIBARRFOUNDATION_PAYMENT_FORM=Per realitzar el pagament de la seva cotització per transferència bancària, visiteu la pàgina <a target="_blank" href="http://wiki.dolibarr.org/index.php/Subscribirse#Para_una_adhesi.C3.B3n_por_transferencia">http://wiki.dolibarr.org/index.php/Subscribirse</a>.<br>Per pagar amb targeta de crèdit o PayPal, feu clic al botó a la part inferior d'aquesta pàgina.<br><br>
diff --git a/htdocs/langs/ca_ES/products.lang b/htdocs/langs/ca_ES/products.lang
index 1c8215343a293ae5f697e109016bb22b396a3c1a..05167ff519c3f6790f38eae6efbb8c36d31aa7cd 100644
--- a/htdocs/langs/ca_ES/products.lang
+++ b/htdocs/langs/ca_ES/products.lang
@@ -1,4 +1,4 @@
-# Dolibarr language file - ca_ES - products
+# Dolibarr language file - ca_ES - products 
 CHARSET=UTF-8
 ProductRef=Ref. producte
 ProductLabel=Etiqueta producte
@@ -168,4 +168,6 @@ CustomerPrices=Preus clients
 SuppliersPrices=Preus proveïdors
 CustomCode=Codi duaner
 CountryOrigin=País d'origen
-HiddenIntoCombo=Ocult en les llistes
\ No newline at end of file
+HiddenIntoCombo=Ocult en les llistes
+ProductCodeModel=Model de codi de producte
+ServiceCodeModel=Model de codi de servei
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index ac8fcccfb3a3db76ff3d1c810476b6499e33b599..d96798483ff583bddbdfdb64ab25d170080eec07 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -637,6 +637,7 @@ Permission1233=Validate supplier invoices
 Permission1234=Delete supplier invoices
 Permission1235=Send supplier invoices by email
 Permission1236=Export supplier invoices, attributes and payments
+Permission1237=Export supplier orders and their details
 Permission1251=Run mass imports of external data into database (data load)
 Permission1321=Export customer invoices, attributes and payments
 Permission1421=Export customer orders and attributes
diff --git a/htdocs/langs/es_ES/admin.lang b/htdocs/langs/es_ES/admin.lang
index 4083cccc6e025d4763dd8cc4eb8b8031be99ab29..4294368ffecb2f748efe9ce4525ca3f7a785ecc6 100644
--- a/htdocs/langs/es_ES/admin.lang
+++ b/htdocs/langs/es_ES/admin.lang
@@ -643,6 +643,7 @@ Permission1233=Validar facturas de proveedores
 Permission1234=Eliminar facturas de proveedores
 Permission1235=Enviar facturas de proveedores por correo
 Permission1236=Exportar facturas de proveedores, atributos y pagos
+Permission1237=Exportar pedidos de proveedores junto con sus detalles
 Permission1251=Lanzar las importaciones en masa a la base de datos (carga de datos)
 Permission1321=Exportar facturas a clientes, atributos y cobros
 Permission1401=Leer el plan contable
diff --git a/htdocs/langs/es_ES/errors.lang b/htdocs/langs/es_ES/errors.lang
index 794c5ba874aef46c241802c4182034d6ba92b0bb..5313ef0cfb4f758ec5a4ffd17770e2d86efbc7d9 100644
--- a/htdocs/langs/es_ES/errors.lang
+++ b/htdocs/langs/es_ES/errors.lang
@@ -113,6 +113,7 @@ ErrorPhpCurlNotInstalled=La extensión PHP CURL no se encuentra instalada, es in
 ErrorFailedToAddToMailmanList=Ha ocurrido un error al intentar añadir un registro a la lista Mailman o base de datos SPIP
 
 # Warnings
+WarningMandatorySetupNotComplete=Los parámetros obligatorios de configuración no están todavía definidos
 WarningSafeModeOnCheckExecDir=Atención, está activada la opción PHP <b>safe_mode</b>, el comando deberá estar dentro de un directorio declarado dentro del parámetro php <b>safe_mode_exec_dir</b>.
 WarningAllowUrlFopenMustBeOn=El parámetro <b>allow_url_fopen</b> debe ser especificado a <b>on</b> en el archivo <b>php.ini</b> para disponer de este módulo completamente activo. Debe modificar este archivo manualmente
 WarningBuildScriptNotRunned=El script <b>%s</b> todavía no ha ejecutado la construcción de gráficos.
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index d79da5b8ff5ab5461b31040fbc6725636e11991f..908ef4ac3313f24417ad9fa42a0faf08e3ae3b43 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -639,6 +639,7 @@ Permission1233= Valider une facture fournisseur
 Permission1234= Supprimer une facture fournisseur
 Permission1235= Envoyer les factures fournisseur par courriel
 Permission1236= Exporter les factures fournisseurs, attributs et règlements
+Permission1237=Exporter les commande fournisseurs, attributs
 Permission1251= Lancer des imports de masse dans la base (chargement de données)
 Permission1321= Exporter les factures clients, attributs et règlements
 Permission1401= Lire le plan de compte
diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php
index 19229f7a953851876caf8bcb7ed89155a167cb8e..1aaa06fee46393e43badc8d0d65ecd7c2e4b5c72 100644
--- a/htdocs/main.inc.php
+++ b/htdocs/main.inc.php
@@ -1289,19 +1289,15 @@ function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $a
 	    if ($_SESSION["dol_authmode"] != 'forceuser'
 	    && $_SESSION["dol_authmode"] != 'http')
 	    {
-	        $logouttext.='<a href="'.DOL_URL_ROOT.'/user/logout.php"';
-	        $logouttext.=$menutop->atarget?(' target="'.$menutop->atarget.'"'):'';
-	        $logouttext.='>';
-	        $logouttext.='<img class="login" border="0" width="14" height="14" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/logout.png"';
-	        $logouttext.=' alt="'.dol_escape_htmltag($langs->trans("Logout")).'" title=""';
-	        $logouttext.='>';
-	        $logouttext.='</a>';
+	        $logouttext .='<a href="'.DOL_URL_ROOT.'/user/logout.php"';
+	        $logouttext .=$menutop->atarget?(' target="'.$menutop->atarget.'"'):'';
+	        $logouttext .='>';
+	        $logouttext .= img_picto($langs->trans('Logout'), 'logout.png', 'class="login"');
+	        $logouttext .='</a>';
 	    }
 	    else
 	    {
-	        $logouttext.='<img class="login" border="0" width="14" height="14" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/logout.png"';
-	        $logouttext.=' alt="'.dol_escape_htmltag($langs->trans("Logout")).'" title=""';
-	        $logouttext.='>';
+	        $logouttext .= img_picto($langs->trans('Logout'), 'logout.png', 'class="login"');
 	    }
 
 	    print '<div class="login_block">'."\n";
@@ -1323,8 +1319,7 @@ function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $a
 	    {
 	        $qs=$_SERVER["QUERY_STRING"].($_SERVER["QUERY_STRING"]?'&':'').$morequerystring;
 	        $text ='<a href="'.$_SERVER["PHP_SELF"].'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
-	        $text.='<img class="printer" border="0" width="14" height="14" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/printer.png"';
-	        $text.=' title="" alt="">';
+	        $text.= img_picto('', 'printer.png', 'class="printer"');
 	        $text.='</a>';
 	        $toprightmenu.=$form->textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'',1);
 	    }
diff --git a/htdocs/product/admin/product.php b/htdocs/product/admin/product.php
index b187f3e170544a5d116c04a26f65ee9a53a3c93d..017fc3cb2ab630ec38b3edf4de1dd75bbe4357e8 100644
--- a/htdocs/product/admin/product.php
+++ b/htdocs/product/admin/product.php
@@ -36,7 +36,7 @@ $langs->load("admin");
 $langs->load("products");
 
 // Security check
-if (! $user->admin || empty($conf->product->enabled))
+if (! $user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled)))
 	accessforbidden();
 
 $action = GETPOST('action','alpha');
diff --git a/htdocs/societe/admin/societe.php b/htdocs/societe/admin/societe.php
index 2029d112457de684002f763fe0df266d59090d08..7b2a51f43872403bd82099bbad826ccedcd5965e 100644
--- a/htdocs/societe/admin/societe.php
+++ b/htdocs/societe/admin/societe.php
@@ -434,7 +434,7 @@ foreach ($dirsociete as $dirroot)
 
 				$modulequalified=1;
 				if (! empty($module->version)) {
-					if ($module->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0;
+					if ($module->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0;
 					else if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0;
 				}
 
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 51b05e910e7bf68a58c579c59cf6f978e99efa64..df8e9849a2422a62e90360c56929919b80cd2cfd 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -212,11 +212,11 @@ class Societe extends CommonObject
         {
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, entity, datec, datea, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm)";
             $sql.= " VALUES ('".$this->db->escape($this->name)."', ".$conf->entity.", '".$this->db->idate($now)."', '".$this->db->idate($now)."'";
-            $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null");
-            $sql.= ", ".($this->canvas ? "'".$this->canvas."'":"null");
+            $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
+            $sql.= ", ".(! empty($this->canvas) ? "'".$this->canvas."'":"null");
             $sql.= ", ".$this->status;
-            $sql.= ", ".($this->ref_int ? "'".$this->ref_int."'":"null");
-            $sql.= ", ".($this->ref_ext ? "'".$this->ref_ext."'":"null");
+            $sql.= ", ".(! empty($this->ref_int) ? "'".$this->ref_int."'":"null");
+            $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->ref_ext."'":"null");
             $sql.= ", 0)";
 
             dol_syslog(get_class($this)."::create sql=".$sql);
@@ -413,8 +413,8 @@ class Societe extends CommonObject
         $this->idprof2		= trim($this->idprof2);
         $this->idprof3		= trim($this->idprof3);
         $this->idprof4		= trim($this->idprof4);
-        $this->idprof5		= trim($this->idprof5);
-        $this->idprof6		= trim($this->idprof6);
+        $this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
+        $this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
         $this->prefix_comm	= trim($this->prefix_comm);
 
         $this->tva_assuj	= trim($this->tva_assuj);
@@ -455,6 +455,32 @@ class Societe extends CommonObject
             return -1;
         }
 
+        $customer=false;
+        if (! empty($allowmodcodeclient) && ! empty($this->client))
+        {
+        	// Attention get_codecompta peut modifier le code suivant le module utilise
+        	if (empty($this->code_compta))
+        	{
+        		$ret=$this->get_codecompta('customer');
+        		if ($ret < 0) return -1;
+        	}
+
+        	$customer=true;
+        }
+
+        $supplier=false;
+        if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
+        {
+        	// Attention get_codecompta peut modifier le code suivant le module utilise
+        	if (empty($this->code_compta_fournisseur))
+        	{
+        		$ret=$this->get_codecompta('supplier');
+        		if ($ret < 0) return -1;
+        	}
+
+        	$supplier=true;
+        }
+
         $this->db->begin();
 
         // Check name is required and codes are ok or unique.
@@ -467,20 +493,20 @@ class Societe extends CommonObject
 
             $sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
             $sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
-            $sql .= ",ref_ext = " .($this->ref_ext?"'".$this->db->escape($this->ref_ext) ."'":"null");
+            $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
             $sql .= ",datea = '".$this->db->idate($now)."'";
             $sql .= ",address = '" . $this->db->escape($this->address) ."'";
 
-            $sql .= ",cp = ".($this->zip?"'".$this->zip."'":"null");
-            $sql .= ",ville = ".($this->town?"'".$this->db->escape($this->town)."'":"null");
+            $sql .= ",cp = ".(! empty($this->zip)?"'".$this->zip."'":"null");
+            $sql .= ",ville = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
 
-            $sql .= ",fk_departement = '" . ($this->state_id?$this->state_id:'0') ."'";
-            $sql .= ",fk_pays = '" . ($this->country_id?$this->country_id:'0') ."'";
+            $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
+            $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
 
-            $sql .= ",tel = ".($this->phone?"'".$this->db->escape($this->phone)."'":"null");
-            $sql .= ",fax = ".($this->fax?"'".$this->db->escape($this->fax)."'":"null");
-            $sql .= ",email = ".($this->email?"'".$this->db->escape($this->email)."'":"null");
-            $sql .= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null");
+            $sql .= ",tel = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
+            $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
+            $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
+            $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
 
             $sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
             $sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
@@ -499,44 +525,36 @@ class Societe extends CommonObject
 
             $sql .= ",capital = ".$this->capital;
 
-            $sql .= ",prefix_comm = ".($this->prefix_comm?"'".$this->db->escape($this->prefix_comm)."'":"null");
+            $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
 
-            $sql .= ",fk_effectif = ".($this->effectif_id?"'".$this->effectif_id."'":"null");
+            $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->effectif_id."'":"null");
 
-            $sql .= ",fk_typent = ".($this->typent_id?"'".$this->typent_id."'":"0");
+            $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->typent_id."'":"0");
 
-            $sql .= ",fk_forme_juridique = ".($this->forme_juridique_code?"'".$this->forme_juridique_code."'":"null");
+            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->forme_juridique_code."'":"null");
 
-            $sql .= ",client = " . ($this->client?$this->client:0);
-            $sql .= ",fournisseur = " . ($this->fournisseur?$this->fournisseur:0);
-            $sql .= ",barcode = ".($this->barcode?"'".$this->barcode."'":"null");
-            $sql .= ",default_lang = ".($this->default_lang?"'".$this->default_lang."'":"null");
-            $sql .= ",logo = ".($this->logo?"'".$this->logo."'":"null");
+            $sql .= ",client = " . (! empty($this->client)?$this->client:0);
+            $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
+            $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->barcode."'":"null");
+            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->default_lang."'":"null");
+            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->logo."'":"null");
 
-            if ($allowmodcodeclient && $this->client)
+            if ($customer)
             {
                 //$this->check_codeclient();
 
-                $sql .= ", code_client = ".($this->code_client?"'".$this->db->escape($this->code_client)."'":"null");
-
-                // Attention get_codecompta peut modifier le code suivant le module utilise
-                if (empty($this->code_compta)) $this->get_codecompta('customer');
-
-                $sql .= ", code_compta = ".($this->code_compta?"'".$this->db->escape($this->code_compta)."'":"null");
+                $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
+                $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
             }
 
-            if ($allowmodcodefournisseur && $this->fournisseur)
+            if ($supplier)
             {
                 //$this->check_codefournisseur();
 
-                $sql .= ", code_fournisseur = ".($this->code_fournisseur?"'".$this->db->escape($this->code_fournisseur)."'":"null");
-
-                // Attention get_codecompta peut modifier le code suivant le module utilise
-                if (empty($this->code_compta_fournisseur)) $this->get_codecompta('supplier');
-
-                $sql .= ", code_compta_fournisseur = ".($this->code_compta_fournisseur?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
+                $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
+                $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
             }
-            $sql .= ", fk_user_modif = ".($user->id > 0 ? "'".$user->id."'":"null");
+            $sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
             $sql .= " WHERE rowid = '" . $id ."'";
 
 
@@ -1803,30 +1821,44 @@ class Societe extends CommonObject
     {
         global $conf;
 
-        if ($conf->global->SOCIETE_CODECOMPTA_ADDON)
+        if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
         {
-            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->societe_modules);
+        	$file='';
+            $dirsociete=array_merge(array('/core/modules/societe/'), $conf->societe_modules);
             foreach ($dirsociete as $dirroot)
             {
-                $res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php");
-                if ($res) break;
+            	if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
+            	{
+            		$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
+            		break;
+            	}
             }
 
-            $var = $conf->global->SOCIETE_CODECOMPTA_ADDON;
-            $mod = new $var;
+            if (! empty($file))
+            {
+            	dol_include_once($file);
 
-            // Defini code compta dans $mod->code
-            $result = $mod->get_code($this->db, $this, $type);
+            	$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
+            	$mod = new $classname;
 
-            if ($type == 'customer') $this->code_compta = $mod->code;
-            if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
+            	// Defini code compta dans $mod->code
+            	$result = $mod->get_code($this->db, $this, $type);
 
-            return $result;
+            	if ($type == 'customer') $this->code_compta = $mod->code;
+            	else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
+
+            	return $result;
+            }
+            else
+            {
+            	$this->error = 'ErrorAccountancyCodeNotDefined';
+            	return -1;
+            }
         }
         else
         {
             if ($type == 'customer') $this->code_compta = '';
-            if ($type == 'supplier') $this->code_compta_fournisseur = '';
+            else if ($type == 'supplier') $this->code_compta_fournisseur = '';
 
             return 0;
         }