diff --git a/ChangeLog b/ChangeLog
index d6ae2f769599586972dd429ba81e16ea33480ef2..85ac7de62a0ca547c2c219230656729c98680c17 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -4,6 +4,7 @@ English Dolibarr ChangeLog
 
 ***** ChangeLog for 3.4 compared to 3.3.2 *****
 For users:
+- New: Event into calendar use different colors for different users.
 - New: Support revenue stamp onto invoices.
 - New: Add a tab "consumption" on thirdparties to list products bought/sells.
 - New: Some performance enhancements.
@@ -30,7 +31,8 @@ For users:
 - New: Can define a different clicktodial setup per user.
 - New: Add option INVOICE_CAN_NEVER_BE_REMOVED.
 - New: Enhance agenda module to reach RFC2445 (add busy information).
-- First change to prepare feature click to print for PDF.
+- New: Add module Opensurvey.
+- First change to prepare feature "click to print" (IPP) for PDF.
   
 For translators:
 - Update language files.
@@ -87,24 +89,6 @@ WARNING: If you used external modules, some of them may need to be upgraded due
 
 
 
-***** ChangeLog for 3.3.2 compared to 3.3.1 *****
-
--Fix: Ducth (nl_NL) translation
--Fix: [ bug #790 ] Spanish localtax RE not being correctly calculated
--Generalize fix: file with a specific mask not found, again
-
-
-
-***** ChangeLog for 3.3.1 compared to 3.3 *****
-
-- Fix: [ bug #733 ] Mass emailing tools do not support <style HTML tag
-- Fix: Package for launchpad
-- Fix: [ bug #736 ] Missing column in llx_c_chargesociales  
-- Fix: Localtax2 for Spain must be based into buyer
-- Fix: [ bug #762 ] Bad profit calculation in Reporting
-
-
-
 ***** ChangeLog for 3.3 compared to 3.2.3 *****
 For users:
 - New: Add holiday module, to declare and follow holidays of your employees.
diff --git a/dev/phpcheckstyle/README b/dev/phpcheckstyle/README
deleted file mode 100644
index 84c6b1bbdc85f0f14214aba614f0c7e3a388ff3a..0000000000000000000000000000000000000000
--- a/dev/phpcheckstyle/README
+++ /dev/null
@@ -1,21 +0,0 @@
-README (English)
---------------------------------
-
-This directory contains example of PHPCheckStyle configuration
-to use for quality assurance on PHP developpement.
-
-To run PHPCheckstyle in eclipse, you must:
-- install plugin PHP Tools integration http://www.phpsrc.org/eclipse/pti/
-- Unzip PHPCheckStyle archive into a directory.
-- Go in Eclipse - Window - Preferences - Dynamic Languages - Validator
-Choose External PHP Script,
-Set path ro run.php file for localhost
-Choose a PHP version, 
-Set parameter string with 
-  --src %f --config "phpstandard.cfg.xml" --format console
-Choose php as Filename extension
-Check Print PHP output to console
-Then add patern
-    * %f INFO Line:%n - %m     Warning
-    * %f WARNING Line:%n - %m  Warning
-    * %f ERROR Line:%n - %m    Error 
\ No newline at end of file
diff --git a/dev/phpcheckstyle/phpstandard.cfg.xml b/dev/phpcheckstyle/phpstandard.cfg.xml
deleted file mode 100644
index 3dd3b314660d4b39a65525e935e95a6a8a0d9681..0000000000000000000000000000000000000000
--- a/dev/phpcheckstyle/phpstandard.cfg.xml
+++ /dev/null
@@ -1,316 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE phpstandard SYSTEM "phpstandard.dtd">
-<!-- somewhat inspired by java checkstyle -->
-<phpcheckstyle-configuration>
-
-    <!--  ****************  -->
-    <!--        Naming      -->
-    <!--  ****************  -->
-    
-    <!-- Check Constant Naming -->
-    <!-- Disabled to avoid warning with $sql="SELECT ..." 
-    <test name="constantNaming" regexp="/^[A-Z_][A-Z_]*[A-Z_]$/" level="ERROR"/>
-    -->
-    
-     <!-- Check Variable Naming -->
-    <test name="variableNaming" regexp="/^[a-zA-Z_][a-zA-Z0-9_]*$/" />
-    
-    <!-- Check Function Naming -->
-    <test name="functionNaming" regexp="/^[a-z_]/" level="WARNING"/>
-    
-    <!-- Check Private Function Naming -->
-    <test name="privateFunctionNaming" regexp="/^[a-z_]/" level="ERROR"/>
-    
-    <!-- Checks the constuctor naming -->
-    <!-- old = old style (constructor = name of the class) -->
-    <!-- new = "__construct()" -->    
-    <test name="constructorNaming">
-        <property name="naming" value="old"/>
-    </test>
-    
-    <!-- Check Class Naming -->
-    <test name="classNaming" regexp="/^[A-Z]/" level="WARNING"/>
-    
-    
-    <!--  ****************  -->
-    <!--      PHP Tags      -->
-    <!--  ****************  -->    
-    
-        
-    <!-- Test if a short php code open tag is used (? instead of ?php ). -->
-    <test name="noShortPhpCodeTag"/>
-    
-    <!-- Test if a PHP closing file is present at the end of a file -->
-    <!-- <test name="noFileCloseTag"/> -->
-    
-    <!-- Test if a file finish with some inner HTML (OK for some view but could provoque "header already sent" error) -->
-    <!-- <test name="noFileFinishHTML" level="ERROR" /> -->
-    
-    
-    <!--  ****************  -->
-    <!--      Comments      -->
-    <!--  ****************  -->    
-    
-    <!-- Check if some C style comments are used (#) -->    
-    <test name="noShellComments"/>
-    
-    <!-- Tests that every function and class is immediately preceded by a docblock. A property "excludePrivateMembers" can be set if you want to disable docblocks for private member functions. -->
-    <test name="docBlocks">
-        <property name="excludePrivateMembers" value="true"/>
-        <property name="testReturn" value="true"/>
-        <property name="testParam" value="true"/>
-        <property name="testThrow" value="true"/>
-    </test>
-
-    
-    <!--  ****************  -->
-    <!--    Indentation     -->
-    <!--  ****************  -->    
-
-    <!-- Tests to make sure that a line does not contain the tab character. -->
-    <!-- <test name="noTabs"/>  -->
-    
-    <!-- Test to make sure that every control structure is included within a {} block, even if it is syntactically optional. -->
-    <!-- <test name="controlStructNeedCurly"/> -->
-    
-    <!-- Check the position of the open curly brace in a control structure (if) -->
-    <!-- sl = same line -->
-    <!-- nl = new line -->
-    <test name="controlStructOpenCurly">
-        <property name="position" value="nl"/>
-    </test>
-
-    <!-- Check the position of the close curly brace  -->
-    <test name="controlCloseCurly" level="INFO">
-    </test>
-        
-    <!-- Check the position of the open curly brace after a function -->
-    <!-- sl = same line -->
-    <!-- nl = new line -->
-    <test name="funcDefinitionOpenCurly">
-        <property name="position" value="nl"/>
-    </test>
-    
-    <!-- Check the position of the else -->
-    <!-- sl = same line -->
-    <!-- nl = new line -->
-    <test name="controlStructElse">
-        <property name="position" value="nl"/>
-    </test>
-    
-    
-    <!--  ****************  -->
-    <!--      Spaces        -->
-    <!--  ****************  --> 
-        
-    <!-- Tests that the control statements ("if", "else", "while", "for", etc.) 
-         are followed by a space before the opening parenthesis. 
-         PEAR standard stipulates this to distinguish it from function calls. 
-    -->
-    <!--
-    <test name="spaceAfterControlStmt"/>
-    -->
-   
-    <!-- Check that there is no space after a function name in a function call -->
-    <!-- <test name="noSpaceAfterFunctionName" level="INFO"></test>  -->  
-     
-    
-    <!-- Check for the (required) presence of a white space after some tokens (like ,) -->
-    <!--
-    <test name="checkWhiteSpaceAfter"> 
-        <exception value="."/>
-    </test>
-    -->
-        
-    <!-- Check for the (required) presence of a white space before some tokens -->
-    <!--
-    <test name="checkWhiteSpaceBefore">
-        <exception value="."/>
-        <exception value=":"/> 
-    </test> 
-    -->
-        
-    <!-- Check that there is no space before before some tokens  -->
-    <!--
-    <test name="noSpaceBeforeToken" level="INFO">
-    </test>
-    -->
-
-    <!-- Check that there is no space after some tokens -->
-    <!--
-    <test name="noSpaceAfterToken"  level="INFO">
-    </test>
-    -->
-    
-    <!--  ****************  -->
-    <!--      Metrics       -->
-    <!--  ****************  --> 
-    
-    <!-- Check that the lenght of the line doesn't pass the max value -->
-    <test name="lineLength" level="INFO">
-        <property name="maxLineLength" value="160"/>
-    </test>
-    
-    <!-- Checks that the lenght (in lines) of a function doesn't pass the max value -->
-    <test name="functionLength" level="INFO">
-        <property name="maxLength" value="500"/>
-    </test>
-    
-    <!--  Checks for excessive parameters in a function declaration -->
-    <!-- <test name="functionMaxParameters">
-        <property name="maxParameters" value="4"/>
-    </test> -->
-    
-    <!-- Check Cyclomatic Complexity -->
-    <!-- see http://www.aivosto.com/project/help/pm-complexity.html -->
-    <test name="cyclomaticComplexity">
-        <!-- Level raising a warning -->
-        <property name="warningLevel" value="10"/>
-        <!-- Level raising an error -->
-        <property name="errorLevel" value="20"/>
-    </test>
-    
-    <!--  ****************  -->
-    <!--      Other         -->
-    <!--  ****************  --> 
-        
-    <!-- All arguments with default values should be at the end -->
-    <test name="defaultValuesOrder"/>
-                    
-    <!-- Check for prohibited functions -->
-    <!-- @see http://www.php.net/manual/en/indexes.php -->
-    <test name="checkProhibitedFunctions">
-        <item value="echo"/>
-        <item value="system"/>
-        <item value="print_r"/>
-        <item value="var_dump"/>
-        <item value="dl"/>
-        <!--<item value="exec"/>-->
-        <item value="passthru"/>
-        <!-- <item value="delete"/> We disable because of false report when using method delete -->
-        <item value="ereg_replace"/>
-        <item value="ereg"/>
-        <item value="eregi"/>
-        <!-- <item value="copy"/>  -->
-        <!-- <item value="fwrite"/>  -->
-    </test>
-    
-    <!-- Check for prohibited tokens -->
-    <!-- @see http://www.php.net/manual/en/tokens.php -->
-    <test name="checkProhibitedTokens">
-        <item value="T_BAD_CHARACTER"/>
-        <item value="T_DECLARE"/>
-        <item value="T_ENDDECLARE"/>
-        <item value="T_ENDFOR"/>
-        <item value="T_ENDFOREACH"/>
-        <item value="T_ENDIF"/>
-        <item value="T_ENDSWITCH"/>
-        <item value="T_ENDWHILE"/>
-        <item value="T_HALT_COMPILER"/>
-        <item value="T_OLD_FUNCTION"/>
-        <!-- <item value="T_PRINT"/> -->
-        
-        <!--  Same thing as the noShortPhpCodeTag rule -->
-        <!-- <item value="T_OPEN_TAG_WITH_ECHO"/> -->
-        
-        <!-- <item value="T_INLINE_HTML"/> -->
-        <!-- <item value="T_ECHO"/>  -->
-        
-        
-    </test>
-    
-     <!-- Check for silenced errors before function calls (@function) -->
-    <test name="checkSilencedError">
-        <exception value="rename"/> <!-- Exceptions to this rule -->
-        <exception value="mkdir"/>
-        <exception value="chmod"/>
-    </test>
-    
-    <!-- Check for encapsed variables inside a String ("$a") -->
-    <test name="encapsedVariablesInsideString">
-    </test>
-    
-     <!-- Avoid passing parameters by reference -->
-    <test name="avoidPassingReferences">
-    </test>
-        
-    <test name="showTODOs">
-    </test>
-    
-    <!-- Use boolean operators (&&) instead of logical operators (AND) -->
-    <test name="useBooleanOperators">
-    </test>
-    
-    <!-- Check empty block like if ($a) {} -->
-    <test name="checkEmptyBlock">
-        <!--  <exception value="catch"/>  -->
-    </test>
-    
-    <!-- Check empty statement ( ;; ) -->
-    <test name="checkEmptyStatement">
-    </test>
-    
-    <!-- Check for the presence of heredoc -->
-    <test name="checkHeredoc">
-    </test>
-    
-    <!-- Check for braces around code blocs (if, else, elseif, do, while, for, foreach) -->
-    <!--
-    <test name="needBraces">
-    </test>
-    -->
-    
-    <!-- Switch need a default value -->
-    <test name="switchNeedDefault">
-    </test>
-    
-     <!-- Switch case should have a break -->
-    <!--  <test name="switchCaseNeedBreak">
-    </test>  -->
-    
-    <!-- Switch default value should be at the end -->
-    <test name="switchDefaultOrder">
-    </test>
-    
-              
-    <!-- 
-    Avoid using unary operators (++) inside a control statement 
-    With the exception of for iterators, all variable incrementation or decrementation should occur in their own toplevel statement to increase readability.  
-    -->
-    <test name="checkUnaryOperator">
-        <exception value="for"/>
-    </test>
-    
-    <!--
-    With inner assignments it is difficult to see all places where a variable is set.
-    With the exception of for iterators, all assignments should occur in their own toplevel statement to increase readability.  
-    -->
-    <test name="checkInnerAssignment">
-        <exception value="for"/>
-    </test>
-    
-    <!-- Detect unused private functions (detecting unused public ones is more difficult) -->
-    <test name="checkUnusedPrivateFunctions">
-    </test>
-    
-    <!-- Detect unused variables -->
-    <test name="checkUnusedVariables">
-    </test>
-    
-    <!-- Detect unused function parameters -->
-    <test name="checkUnusedFunctionParameters">
-    </test>
-    
-    <!-- Only one class declaration per PHP file -->
-    <test name="oneClassPerFile">
-    </test>
-    
-    <!--  *******************  -->
-    <!--      Optimisation     -->
-    <!--  *******************  --> 
-    
-    <!-- Only one class declaration per PHP file -->
-    <test name="functionInsideLoop">
-    </test>
-    
-</phpcheckstyle-configuration>
\ No newline at end of file
diff --git a/dev/phpcheckstyle/phpstandard.dtd b/dev/phpcheckstyle/phpstandard.dtd
deleted file mode 100644
index bde6e6b2b52cfb29de15e3e550488157916f99f6..0000000000000000000000000000000000000000
--- a/dev/phpcheckstyle/phpstandard.dtd
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!ELEMENT phpcheckstyle-configuration (test+)>
-<!ELEMENT test (property*,item*,exception*)>
-<!ATTLIST test name CDATA "">
-<!ATTLIST test regexp CDATA "">
-<!ATTLIST test level CDATA "">
-<!ELEMENT property (#PCDATA)>
-<!ATTLIST property value CDATA "">
-<!ATTLIST property name CDATA "">
-<!ELEMENT item (#PCDATA)>
-<!ATTLIST item value CDATA "">
-<!ELEMENT exception (#PCDATA)>
-<!ATTLIST exception value CDATA "">
diff --git a/htdocs/adherents/fiche.php b/htdocs/adherents/fiche.php
index dda805ec1132a8d79e240f6baeafe515ece10511..65c79d66068924aa66cedc97a8c189238bd55205 100644
--- a/htdocs/adherents/fiche.php
+++ b/htdocs/adherents/fiche.php
@@ -49,8 +49,8 @@ $backtopage=GETPOST('backtopage','alpha');
 $confirm=GETPOST('confirm','alpha');
 $rowid=GETPOST('rowid','int');
 $typeid=GETPOST('typeid','int');
-$userid=GETPOST('userid','int');
-$socid=GETPOST('socid','int');
+$userid=GETPOST('userid','int');
+$socid=GETPOST('socid','int');
 
 if (! empty($conf->mailmanspip->enabled))
 {
@@ -68,7 +68,7 @@ $extrafields = new ExtraFields($db);
 $extralabels=$extrafields->fetch_name_optionals_label('member');
 
 // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
-$object->getCanvas($socid);
+$object->getCanvas($rowid);
 $canvas = $object->canvas?$object->canvas:GETPOST("canvas");
 $objcanvas='';
 if (! empty($canvas))
@@ -117,7 +117,7 @@ $hookmanager->initHooks(array('membercard'));
  * 	Actions
 */
 
-$parameters=array('socid'=>$socid, 'objcanvas'=>$objcanvas);
+$parameters=array('rowid'=>$rowid, 'objcanvas'=>$objcanvas);
 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
 
 if ($action == 'setuserid' && ($user->rights->user->self->creer || $user->rights->user->user->creer))
@@ -694,13 +694,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
 	// -----------------------------------------
 	// When used with CANVAS
 	// -----------------------------------------
-	if (empty($object->error) && $socid)
+	if (empty($object->error) && $rowid)
 	{
 		$object = new Adherent($db);
-		$object->fetch($socid);
+		$result=$object->fetch($rowid);
+		if ($result <= 0) dol_print_error('',$object->error);
 	}
-	$objcanvas->assign_values($action, $socid);	// Set value for templates
-	$objcanvas->display_canvas($action);		// Show template
+   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
+    $objcanvas->display_canvas($action);							// Show template
 }
 else
 {
diff --git a/htdocs/adherents/note.php b/htdocs/adherents/note.php
index c021ab5a373aef084151e933471c136a67c6eacf..d92447434d4f994845d2477c9a481451e8a07d9c 100644
--- a/htdocs/adherents/note.php
+++ b/htdocs/adherents/note.php
@@ -54,7 +54,7 @@ if ($action == 'update' && $user->rights->adherent->creer && ! $_POST["cancel"])
 {
 	$db->begin();
 
-	$res=$object->update_note($_POST["note"],$user);
+	$res=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
 	if ($res < 0)
 	{
 		setEventMessage($object->error, 'errors');
diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php
index deb32ce29d0fbe5ceee0c192ca1a4914800c42de..2120d2d2a83bad1960967fb9f0c20eca0239affa 100644
--- a/htdocs/adherents/type.php
+++ b/htdocs/adherents/type.php
@@ -146,7 +146,7 @@ if ($action == 'commentaire' && $user->rights->adherent->configurer)
 {
 	$don = new Don($db);
 	$don->fetch($rowid);
-	$don->update_note($_POST["commentaire"]);
+	$don->update_note(dol_html_entity_decode(GETPOST('commentaire'), ENT_QUOTES));
 }
 
 
diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php
index ebcb94110e9c0afcfa5bca70c83d5b62e731ff0b..23295efa17af4963359a0b50545c9befa275e2bb 100644
--- a/htdocs/admin/commande.php
+++ b/htdocs/admin/commande.php
@@ -188,7 +188,7 @@ else if ($action == 'set_COMMANDE_FREE_TEXT')
         $mesg = "<font class=\"error\">".$langs->trans("Error")."</font>";
     }
 }
-else if ($action='setModuleOptions') {
+else if ($action=='setModuleOptions') {
 	if (dolibarr_set_const($db, "COMMANDE_ADDON_PDF_ODT_PATH",GETPOST('value1'),'chaine',0,'',$conf->entity))
 	{
 		// La constante qui a ete lue en avant du nouveau set
diff --git a/htdocs/admin/project.php b/htdocs/admin/project.php
index 9f28b57be5b491d87933d0f4cef5a590cf5de12d..e9973758c7360d47143f14b740eebeae7eb55b4d 100644
--- a/htdocs/admin/project.php
+++ b/htdocs/admin/project.php
@@ -152,7 +152,8 @@ else if ($action == 'setmod')
 
 	dolibarr_set_const($db, "PROJECT_ADDON",$value,'chaine',0,'',$conf->entity);
 }
-else if ($action='setModuleOptions') {
+
+else if ($action=='setModuleOptions') {
 	if (dolibarr_set_const($db, "PROJECT_ADDON_PDF_ODT_PATH",GETPOST('value1'),'chaine',0,'',$conf->entity))
 	{
 		// La constante qui a ete lue en avant du nouveau set
diff --git a/htdocs/admin/supplierinvoice_extrafields.php b/htdocs/admin/supplierinvoice_extrafields.php
new file mode 100644
index 0000000000000000000000000000000000000000..a95a61c98cfebbaa4488653da851e068a6bd33dd
--- /dev/null
+++ b/htdocs/admin/supplierinvoice_extrafields.php
@@ -0,0 +1,160 @@
+<?php
+/* Copyright (C) 2001-2002	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
+ * Copyright (C) 2003		Jean-Louis Bergamo		<jlb@j1b.org>
+ * Copyright (C) 2004-2013	Laurent Destailleur		<eldy@users.sourceforge.net>
+ * Copyright (C) 2012		Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2012		Florian Henry			<florian.henry@open-concept.pro>
+ * Copyright (C) 2013		Philippe Grand			<philippe.grand@atoo-net.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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *      \file       htdocs/admin/supplierinvoice_extrafields.php
+ *		\ingroup    fourn
+ *		\brief      Page to setup extra fields of supplierinvoice
+ */
+
+require '../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+
+
+if (!$user->admin)
+	accessforbidden();
+
+$langs->load("admin");
+$langs->load("other");
+$langs->load("orders");
+$langs->load("suppliers");
+
+$extrafields = new ExtraFields($db);
+$form = new Form($db);
+
+// List of supported format
+$tmptype2label=getStaticMember(get_class($extrafields),'type2label');
+$type2label=array('');
+foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val);
+
+$action=GETPOST('action', 'alpha');
+$attrname=GETPOST('attrname', 'alpha');
+$elementtype='commande_fournisseur';
+
+if (!$user->admin) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+require DOL_DOCUMENT_ROOT.'/core/admin_extrafields.inc.php';
+
+
+
+/*
+ * View
+ */
+
+$textobject=$langs->transnoentitiesnoconv("SuppliersInvoices");
+
+llxHeader('',$langs->trans("SuppliersSetup"));
+
+$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
+print_fiche_titre($langs->trans("SuppliersSetup"),$linkback,'setup');
+print "<br>\n";
+
+$head = supplierorder_admin_prepare_head(null);
+
+dol_fiche_head($head, 'supplierinvoice', $langs->trans("ModuleSetup"), 0, 'invoice');
+
+
+print $langs->trans("DefineHereComplementaryAttributes",$textobject).'<br>'."\n";
+print '<br>';
+
+// Load attribute_label
+$extrafields->fetch_name_optionals_label($elementtype);
+
+print "<table summary=\"listofattributes\" class=\"noborder\" width=\"100%\">";
+
+print '<tr class="liste_titre">';
+print '<td>'.$langs->trans("Label").'</td>';
+print '<td>'.$langs->trans("AttributeCode").'</td>';
+print '<td>'.$langs->trans("Type").'</td>';
+print '<td align="right">'.$langs->trans("Size").'</td>';
+print '<td align="center">'.$langs->trans("Unique").'</td>';
+print '<td align="center">'.$langs->trans("Required").'</td>';
+print '<td width="80">&nbsp;</td>';
+print "</tr>\n";
+
+$var=True;
+foreach($extrafields->attribute_type as $key => $value)
+{
+    $var=!$var;
+    print "<tr ".$bc[$var].">";
+    print "<td>".$extrafields->attribute_label[$key]."</td>\n";
+    print "<td>".$key."</td>\n";
+    print "<td>".$type2label[$extrafields->attribute_type[$key]]."</td>\n";
+    print '<td align="right">'.$extrafields->attribute_size[$key]."</td>\n";
+    print '<td align="center">'.yn($extrafields->attribute_unique[$key])."</td>\n";
+    print '<td align="center">'.yn($extrafields->attribute_required[$key])."</td>\n";
+    print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit&attrname='.$key.'">'.img_edit().'</a>';
+    print "&nbsp; <a href=\"".$_SERVER["PHP_SELF"]."?action=delete&attrname=$key\">".img_delete()."</a></td>\n";
+    print "</tr>";
+}
+
+print "</table>";
+
+dol_fiche_end();
+
+
+// Buttons
+if ($action != 'create' && $action != 'edit')
+{
+    print '<div class="tabsAction">';
+    print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute")."</a>";
+    print "</div>";
+}
+
+
+/* ************************************************************************** */
+/*                                                                            */
+/* Creation d'un champ optionnel											  */
+/*                                                                            */
+/* ************************************************************************** */
+
+if ($action == 'create')
+{
+    print "<br>";
+    print_titre($langs->trans('NewAttribute'));
+
+    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
+}
+
+/* ************************************************************************** */
+/*                                                                            */
+/* Edition d'un champ optionnel                                               */
+/*                                                                            */
+/* ************************************************************************** */
+if ($action == 'edit' && ! empty($attrname))
+{
+    print "<br>";
+    print_titre($langs->trans("FieldEdition", $attrname));
+
+    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
+}
+
+llxFooter();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/admin/supplierorder_extrafields.php b/htdocs/admin/supplierorder_extrafields.php
index 9322d034931dc3410067528509d0bccca4025b52..68747cf417cc15f3d206eb51f5708674253474c0 100644
--- a/htdocs/admin/supplierorder_extrafields.php
+++ b/htdocs/admin/supplierorder_extrafields.php
@@ -65,7 +65,7 @@ require DOL_DOCUMENT_ROOT.'/core/admin_extrafields.inc.php';
  * View
  */
 
-$textobject=$langs->transnoentitiesnoconv("SupplierOrder");
+$textobject=$langs->transnoentitiesnoconv("SuppliersOrders");
 
 llxHeader('',$langs->trans("SuppliersSetup"));
 
@@ -75,7 +75,7 @@ print "<br>\n";
 
 $head = supplierorder_admin_prepare_head(null);
 
-dol_fiche_head($head, 'attributes', $langs->trans("ModuleSetup"), 0, 'order');
+dol_fiche_head($head, 'supplierorder', $langs->trans("ModuleSetup"), 0, 'order');
 
 
 print $langs->trans("DefineHereComplementaryAttributes",$textobject).'<br>'."\n";
diff --git a/htdocs/admin/system/modules.php b/htdocs/admin/system/modules.php
index bfd1bc5d81f2b8c31a439a06f0b9fcad1f674c2b..0baed9e53bc86300a8653ab1d882ba439be3f2cc 100644
--- a/htdocs/admin/system/modules.php
+++ b/htdocs/admin/system/modules.php
@@ -47,9 +47,11 @@ print "<br>\n";
 $modules = array();
 $modules_names = array();
 $modules_files = array();
+$modules_fullpath = array();
 $modulesdir = dolGetModulesDirs();
 
 // Load list of modules
+$i=0;
 foreach($modulesdir as $dir)
 {
 	$handle=@opendir(dol_osencode($dir));
@@ -63,13 +65,25 @@ foreach($modulesdir as $dir)
 
     			if ($modName)
     			{
-    				include_once $dir.$file;
-    				$objMod = new $modName($db);
+    				//print 'xx'.$dir.$file.'<br>';
+					if (in_array($file, $modules_files))
+					{
+						// File duplicate
+						print "Warning duplicate file found : ".$file." (Found ".$dir.$file.", already found ".$modules_fullpath[$file].")<br>";
+					}
+					else
+					{
+						// File to load
+    					include_once $dir.$file;
 
-    				$modules[$objMod->numero]=$objMod;
-    				$modules_names[$objMod->numero]=$objMod->name;
-    				$modules_files[$objMod->numero]=$file;
-    				$picto[$objMod->numero]=(isset($objMod->picto) && $objMod->picto)?$objMod->picto:'generic';
+	    				$objMod = new $modName($db);
+
+	    				$modules[$objMod->numero]=$objMod;
+	    				$modules_names[$objMod->numero]=$objMod->name;
+	    				$modules_files[$objMod->numero]=$file;
+	    				$modules_fullpath[$file]=$dir.$file;
+	    				$picto[$objMod->numero]=(isset($objMod->picto) && $objMod->picto)?$objMod->picto:'generic';
+					}
     			}
     		}
     	}
@@ -127,8 +141,7 @@ sort($rights_ids);
 $old='';
 foreach($rights_ids as $right_id)
 {
-	if ($old == $right_id)
-		print "Warning duplicate id on permission : ".$right_id."<br>";
+	if ($old == $right_id) print "Warning duplicate id on permission : ".$right_id."<br>";
 	$old = $right_id;
 }
 
diff --git a/htdocs/categories/categorie.php b/htdocs/categories/categorie.php
index b1532f5d7d7042643d64576a1643d59cf220d000..ddc7079c7866211b4b8f2422c5c8290d05f6b4e0 100644
--- a/htdocs/categories/categorie.php
+++ b/htdocs/categories/categorie.php
@@ -240,7 +240,9 @@ if ($socid)
 	}
 
 	// Address
-	print '<tr><td valign="top">'.$langs->trans('Address').'</td><td colspan="3">'.nl2br($soc->address).'</td></tr>';
+	print '<tr><td valign="top">'.$langs->trans('Address').'</td><td colspan="3">';
+    print dol_print_address($soc->address,'gmap','thirdparty',$object->id);
+    print '</td></tr>';
 
 	// Zip / Town
 	print '<tr><td width="25%">'.$langs->trans('Zip').'</td><td width="25%">'.$soc->zip."</td>";
diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php
index c2c249f5e41edad34f438b01f6545aab68150fac..96c111f2dc0c15084366811d8d3b65363a9bec51 100644
--- a/htdocs/categories/class/categorie.class.php
+++ b/htdocs/categories/class/categorie.class.php
@@ -477,7 +477,7 @@ class Categorie
 
 
 	/**
-	 * Retourne les filles de la categorie
+	 * Return childs of a category
 	 *
 	 * @return	void
 	 */
@@ -507,43 +507,6 @@ class Categorie
 	}
 
 
-	/**
-	 * Return category description
-	 *
-	 * @param	int		$cate		Category id
-	 * @return	string				Description
-	 * @deprecated function not used ?
-	 */
-	function get_desc($cate)
-	{
-		$sql = "SELECT description FROM ".MAIN_DB_PREFIX."categorie";
-		$sql.= " WHERE rowid = ".$cate;
-
-		$res = $this->db->query($sql);
-		$n   = $this->db->fetch_array($res);
-
-		return($n[0]);
-	}
-
-	/**
-	 * La categorie $fille est-elle une fille de cette categorie ?
-	 *
-	 * @param	Category	$child		Object category
-	 * @return	void
-	 * @deprecated function not used ?
-	 */
-	function is_fille($child)
-	{
-		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
-		$sql.= " WHERE fk_parent = ".$this->id." AND rowid = ".$child->id;
-
-		$res  = $this->db->query($sql);
-		$n    = $this->db->fetch_array($res);
-
-		return ($n[0] > 0);
-	}
-
-
 	/**
 	 * 	Load this->motherof that is array(id_son=>id_parent, ...)
 	 *
diff --git a/htdocs/comm/action/fiche.php b/htdocs/comm/action/fiche.php
index 5ed00c1fd6e04ca0cdf279f7168df22fe4b164dc..37c5aaba693913ff2311b6d37c841df31d6288a3 100644
--- a/htdocs/comm/action/fiche.php
+++ b/htdocs/comm/action/fiche.php
@@ -589,8 +589,6 @@ if ($action == 'create')
 	print '<input type="text" name="priority" value="'.(GETPOST('priority')?GETPOST('priority'):($actioncomm->priority?$actioncomm->priority:'')).'" size="5">';
 	print '</td></tr>';
 
-	add_row_for_calendar_link();
-
     // Description
     print '<tr><td valign="top">'.$langs->trans("Description").'</td><td>';
     require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
@@ -1061,90 +1059,8 @@ if ($id > 0)
 	print '</div>';
 }
 
+
 llxFooter();
 
 $db->close();
-
-
-/**
- *  Ajoute une ligne de tableau a 2 colonnes pour avoir l'option synchro calendrier
- *
- *  @return     int     Retourne le nombre de lignes ajoutees
- */
-function add_row_for_calendar_link()
-{
-	global $conf,$langs,$user;
-	$nbtr=0;
-
-	// Lien avec calendrier si module active
-	// TODO external module
-	if (! empty($conf->webcalendar->enabled))
-	{
-		if ($conf->global->PHPWEBCALENDAR_SYNCRO != 'never')
-		{
-			$langs->load("other");
-
-			print '<tr><td width="25%" nowrap>'.$langs->trans("AddCalendarEntry","Webcalendar").'</td>';
-
-			if (! $user->webcal_login)
-			{
-				print '<td><input type="checkbox" disabled name="add_webcal">';
-				print ' '.$langs->transnoentities("ErrorWebcalLoginNotDefined","<a href=\"".DOL_URL_ROOT."/user/fiche.php?id=".$user->id."\">".$user->login."</a>");
-				print '</td>';
-				print '</tr>';
-				$nbtr++;
-			}
-			else
-			{
-				if ($conf->global->PHPWEBCALENDAR_SYNCRO == 'always')
-				{
-					print '<input type="hidden" name="add_webcal" value="on">';
-				}
-				else
-				{
-					print '<td><input type="checkbox" name="add_webcal"'.(($conf->global->PHPWEBCALENDAR_SYNCRO=='always' || $conf->global->PHPWEBCALENDAR_SYNCRO=='yesbydefault')?' checked':'').'></td>';
-					print '</tr>';
-					$nbtr++;
-				}
-			}
-		}
-	}
-
-	// TODO external module
-	if (! empty($conf->phenix->enabled))
-	{
-		if ($conf->global->PHPPHENIX_SYNCRO != 'never')
-		{
-			$langs->load("other");
-
-			print '<tr><td width="25%" nowrap>'.$langs->trans("AddCalendarEntry","Phenix").'</td>';
-
-			if (! $user->phenix_login)
-			{
-				print '<td><input type="checkbox" disabled name="add_phenix">';
-				print ' '.$langs->transnoentities("ErrorPhenixLoginNotDefined","<a href=\"".DOL_URL_ROOT."/user/fiche.php?id=".$user->id."\">".$user->login."</a>");
-				print '</td>';
-				print '</tr>';
-				$nbtr++;
-			}
-			else
-			{
-				if ($conf->global->PHPPHENIX_SYNCRO == 'always')
-				{
-					print '<input type="hidden" name="add_phenix" value="on">';
-				}
-				else
-				{
-					print '<td><input type="checkbox" name="add_phenix"'.(($conf->global->PHPPHENIX_SYNCRO=='always' || $conf->global->PHPPHENIX_SYNCRO=='yesbydefault')?' checked':'').'></td>';
-					print '</tr>';
-					$nbtr++;
-				}
-			}
-		}
-	}
-
-	return $nbtr;
-}
-
-
 ?>
diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php
index 0b182c7645ffb70e4c0d0740a1b2fa6c74929d1b..49a84a28d227710984e379f06a1b5508d83f0b06 100644
--- a/htdocs/comm/action/index.php
+++ b/htdocs/comm/action/index.php
@@ -942,7 +942,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     global $user, $conf, $langs;
     global $filter, $filtera, $filtert, $filterd, $status;
     global $theme_datacolor;
-    global $cachethirdparties, $cachecontacts;
+    global $cachethirdparties, $cachecontacts, $colorindexused;
 
     print '<div id="dayevent_'.sprintf("%04d",$year).sprintf("%02d",$month).sprintf("%02d",$day).'" class="dayevent">'."\n";
     $curtime = dol_mktime(0, 0, 0, $month, $day, $year);
@@ -972,6 +972,9 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     $i=0; $nummytasks=0; $numother=0; $numbirthday=0; $numical=0; $numicals=array();
     $ymd=sprintf("%04d",$year).sprintf("%02d",$month).sprintf("%02d",$day);
 
+    $nextindextouse=count($colorindexused);
+	//print $nextindextouse;
+
     foreach ($eventarray as $daykey => $notused)
     {
         $annee = date('Y',$daykey);
@@ -989,10 +992,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                     $color=-1; $cssclass=''; $colorindex=-1;
                     if ((! empty($event->author->id) && $event->author->id == $user->id)
                     || (! empty($event->usertodo->id) && $event->usertodo->id == $user->id)
-                    || (! empty($event->userdone->id) && $event->userdone->id == $user->id)) {
-                    	$nummytasks++; $colorindex=1; $cssclass='family_mytasks';
+                    || (! empty($event->userdone->id) && $event->userdone->id == $user->id))
+                    {
+                    	$nummytasks++; $cssclass='family_mytasks';
                     }
-                    else if ($event->type_code == 'ICALEVENT') {
+                    else if ($event->type_code == 'ICALEVENT')
+                    {
                     	$numical++;
                     	if (! empty($event->icalname)) {
                     		if (! isset($numicals[dol_string_nospecial($event->icalname)])) {
@@ -1004,8 +1009,25 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
                     	$cssclass=(! empty($event->icalname)?'family_'.dol_string_nospecial($event->icalname):'family_other');
                     }
                     else if ($event->type_code == 'BIRTHDAY')  { $numbirthday++; $colorindex=2; $cssclass='family_birthday'; }
-                    else { $numother++; $colorindex=2; $cssclass='family_other'; }
-                    if ($color == -1) $color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]);
+                    else { $numother++; $cssclass='family_other'; }
+                    if ($color == -1)	// Color was not forced. Set color according to color index.
+                    {
+                    	// Define color index if not yet defined
+                    	$idusertouse=($event->usertodo->id?$event->usertodo->id:0);
+                    	if (isset($colorindexused[$idusertouse]))
+                    	{
+                    		$colorindex=$colorindexused[$idusertouse];	// Color already assigned to this user
+                    	}
+                    	else
+                    	{
+                    		$colorindex=$nextindextouse;
+                    		$colorindexused[$idusertouse]=$colorindex;
+                    		if (! empty($theme_datacolor[$nextindextouse+1])) $nextindextouse++;	// Prepare to use next color
+                    	}
+                    	//print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'<br>';
+						// Define color
+                    	$color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]);
+                    }
                     $cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd;
 
                     // Show rect of event
@@ -1182,6 +1204,13 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
     print '</div>'."\n";
 }
 
+/**
+ * Change color with a delta
+ *
+ * @param	string	$color		Color
+ * @param 	int		$minus		Delta
+ * @return	string				New color
+ */
 function dol_color_minus($color, $minus)
 {
 	$newcolor=$color;
diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index 95bb905348fc4a46593c7288a783c5e9107acab8..22c7de7c5f27e382391974dd0800a1f168c8ad68 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
- * Copyright (C) 2005-2010 Laurent Destailleur  <eldy@uers.sourceforge.net>
+ * Copyright (C) 2005-2013 Laurent Destailleur  <eldy@uers.sourceforge.net>
  * Copyright (C) 2005-2010 Regis Houssin        <regis.houssin@capnetworks.com>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -307,7 +307,7 @@ if ($object->fetch($id) >= 0)
 					 print $modulename;
 					 print "</td>";
 					 */
-					$nbofrecipient=$obj->getNbOfRecipients();
+					$nbofrecipient=$obj->getNbOfRecipients('');
 					print '<td align="center">';
 					if ($nbofrecipient >= 0)
 					{
@@ -346,21 +346,8 @@ if ($object->fetch($id) >= 0)
 
 		print '</table>';
 		print '<br>';
-
-		print '<form action="'.$_SERVER['PHP_SELF'].'?action=clear&id='.$object->id.'" method="POST">';
-		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-		print_titre($langs->trans("ToClearAllRecipientsClickHere"));
-		print '<table class="noborder" width="100%">';
-		print '<tr class="liste_titre">';
-		print '<td class="liste_titre" align="right"><input type="submit" class="button" value="'.$langs->trans("TargetsReset").'"></td>';
-		print '</tr>';
-		print '</table>';
-		print '</form>';
-		print '<br>';
 	}
 
-
-
 	// List of selected targets
 	print "\n<!-- Liste destinataires selectionnes -->\n";
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@@ -383,21 +370,23 @@ if ($object->fetch($id) >= 0)
 	{
 		$num = $db->num_rows($resql);
 
-		$parm = "&amp;id=".$object->id;
-		if ($search_lastname)    $parm.= "&amp;search_lastname=".urlencode($search_lastname);
-		if ($search_firstname) $parm.= "&amp;search_firstname=".urlencode($search_firstname);
-		if ($search_email)  $parm.= "&amp;search_email=".urlencode($search_email);
+		$param = "&amp;id=".$object->id;
+		if ($search_lastname)  $param.= "&amp;search_lastname=".urlencode($search_lastname);
+		if ($search_firstname) $param.= "&amp;search_firstname=".urlencode($search_firstname);
+		if ($search_email)     $param.= "&amp;search_email=".urlencode($search_email);
+
+		$cleartext='<br></div><div>'.$langs->trans("ToClearAllRecipientsClickHere").': '.'<input type="submit" class="button" value="'.$langs->trans("TargetsReset").'">';
 
-		print_barre_liste($langs->trans("MailSelectedRecipients"),$page,$_SERVER["PHP_SELF"],$parm,$sortfield,$sortorder,"",$num,$object->nbemail,'');
+		print_barre_liste($langs->trans("MailSelectedRecipients").$cleartext,$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,"",$num,$object->nbemail,'');
 
-		if ($page)			$parm.= "&amp;page=".$page;
+		if ($page)			$param.= "&amp;page=".$page;
 		print '<table class="noborder" width="100%">';
 		print '<tr class="liste_titre">';
-		print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"mc.email",$parm,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"mc.lastname",$parm,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"mc.firstname",$parm,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("OtherInformations"),$_SERVER["PHP_SELF"],"",$parm,"","",$sortfield,$sortorder);
-		print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"],"",$parm,"",'align="center"',$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"mc.email",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"mc.lastname",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"mc.firstname",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("OtherInformations"),$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"],"",$param,"",'align="center"',$sortfield,$sortorder);
 
 		// Date sendinf
 		if ($object->statut < 2)
@@ -406,11 +395,11 @@ if ($object->fetch($id) >= 0)
 		}
 		else
 		{
-			print_liste_field_titre($langs->trans("DateSending"),$_SERVER["PHP_SELF"],"mc.date_envoi",$parm,'','align="center"',$sortfield,$sortorder);
+			print_liste_field_titre($langs->trans("DateSending"),$_SERVER["PHP_SELF"],"mc.date_envoi",$param,'','align="center"',$sortfield,$sortorder);
 		}
 
 		// Statut
-		print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"mc.statut",$parm,'','align="right"',$sortfield,$sortorder);
+		print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"mc.statut",$param,'','align="right"',$sortfield,$sortorder);
 
 		print '</tr>';
 
@@ -496,7 +485,7 @@ if ($object->fetch($id) >= 0)
 					print '<td align="center">&nbsp;</td>';
 					print '<td align="right" nowrap="nowrap">'.$langs->trans("MailingStatusNotSent");
 					if ($user->rights->mailing->creer) {
-						print '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&rowid='.$obj->rowid.$parm.'">'.img_delete($langs->trans("RemoveRecipient"));
+						print '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&rowid='.$obj->rowid.$param.'">'.img_delete($langs->trans("RemoveRecipient"));
 					}
 					print '</td>';
 				}
diff --git a/htdocs/comm/propal.php b/htdocs/comm/propal.php
index 42bf3e5d084c5e4df5f61a38cb9ffe27273a2e82..9c77da6776588acfe9cb0f2220ef4cd046736496 100644
--- a/htdocs/comm/propal.php
+++ b/htdocs/comm/propal.php
@@ -8,7 +8,8 @@
  * Copyright (C) 2010-2013 Juanjo Menent         <jmenent@2byte.es>
  * Copyright (C) 2010-2011 Philippe Grand        <philippe.grand@atoo-net.com>
  * Copyright (C) 2012      Christophe Battarel   <christophe.battarel@altairis.fr>
-*
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
+ * 
  * 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
@@ -233,13 +234,13 @@ else if ($action == 'set_ref_client' && $user->rights->propal->creer)
 
 else if ($action == 'setnote_public' && $user->rights->propal->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->propal->creer)
+else if ($action == 'setnote_private' && $user->rights->propal->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php
index 13d2e6e87a46a644466edb9ce0884ca7f21cfa87..1c514dd679af8346e36f2925f59798acfa4a2399 100644
--- a/htdocs/comm/propal/class/propal.class.php
+++ b/htdocs/comm/propal/class/propal.class.php
@@ -8,7 +8,8 @@
  * Copyright (C) 2008      Raphael Bertrand			<raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2013 Juanjo Menent			<jmenent@2byte.es>
  * Copyright (C) 2010-2011 Philippe Grand			<philippe.grand@atoo-net.com>
- * Copyright (C) 2012      Christophe Battarel  <christophe.battarel@altairis.fr>
+ * Copyright (C) 2012      Christophe Battarel  	<christophe.battarel@altairis.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -673,7 +674,7 @@ class Propal extends CommonObject
         $sql.= ", datec";
         $sql.= ", ref";
         $sql.= ", fk_user_author";
-        $sql.= ", note";
+        $sql.= ", note_private";
         $sql.= ", note_public";
         $sql.= ", model_pdf";
         $sql.= ", fin_validite";
@@ -698,7 +699,7 @@ class Propal extends CommonObject
         $sql.= ", '".$this->db->idate($now)."'";
         $sql.= ", '(PROV)'";
         $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"null");
-        $sql.= ", '".$this->db->escape($this->note)."'";
+        $sql.= ", '".$this->db->escape($this->note_private)."'";
         $sql.= ", '".$this->db->escape($this->note_public)."'";
         $sql.= ", '".$this->modelpdf."'";
         $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"null");
@@ -1000,7 +1001,7 @@ class Propal extends CommonObject
         $sql.= ", p.fin_validite as dfv";
         $sql.= ", p.date_livraison as date_livraison";
         $sql.= ", p.model_pdf, p.ref_client, p.extraparams";
-        $sql.= ", p.note as note_private, p.note_public";
+        $sql.= ", p.note_private, p.note_public";
         $sql.= ", p.fk_projet, p.fk_statut";
         $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
         $sql.= ", p.fk_delivery_address";
@@ -1584,7 +1585,7 @@ class Propal extends CommonObject
         $this->db->begin();
 
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
-        $sql.= " SET fk_statut = ".$statut.", note = '".$this->db->escape($note)."', date_cloture=".$this->db->idate($now).", fk_user_cloture=".$user->id;
+        $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture=".$this->db->idate($now).", fk_user_cloture=".$user->id;
         $sql.= " WHERE rowid = ".$this->id;
 
         $resql=$this->db->query($sql);
@@ -1614,7 +1615,7 @@ class Propal extends CommonObject
         $this->db->begin();
 
         $sql = "UPDATE ".MAIN_DB_PREFIX."propal";
-        $sql.= " SET fk_statut = ".$statut.", note = '".$this->db->escape($note)."', date_cloture=".$this->db->idate($now).", fk_user_cloture=".$user->id;
+        $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture=".$this->db->idate($now).", fk_user_cloture=".$user->id;
         $sql.= " WHERE rowid = ".$this->id;
 
         $resql=$this->db->query($sql);
@@ -2322,7 +2323,7 @@ class Propal extends CommonObject
         $this->demand_reason_id    = 1;
         $this->demand_reason_code  = 'SRC_00';
         $this->note_public='This is a comment (public)';
-        $this->note='This is a comment (private)';
+        $this->note_private='This is a comment (private)';
         // Lines
         $nbp = 5;
         $xnbp = 0;
diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php
index 4603bd82682905dacb9562ab5650b41b509906f3..09670340b891d199976ff6d7eec670ca0431ad72 100644
--- a/htdocs/comm/propal/note.php
+++ b/htdocs/comm/propal/note.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2012 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2004      Eric Seigne          <eric.seigne@ryxeo.com>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -50,14 +51,14 @@ $object = new Propal($db);
 if ($action == 'setnote_public' && $user->rights->propale->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->propale->creer)
+else if ($action == 'setnote_private' && $user->rights->propale->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php
index cab6e77be23cac898bc68200fd8645cc77c5b273..b6e11a64065043e1b2df57067332f00d4fba6674 100644
--- a/htdocs/commande/class/commande.class.php
+++ b/htdocs/commande/class/commande.class.php
@@ -6,6 +6,7 @@
  * Copyright (C) 2010-2012 Juanjo Menent        <jmenent@2byte.es>
  * Copyright (C) 2011      Jean Heimburger      <jean@tiaris.info>
  * Copyright (C) 2012      Christophe Battarel  <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -630,7 +631,7 @@ class Commande extends CommonOrder
         $this->db->begin();
 
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
-        $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note, note_public, ref_client, ref_int";
+        $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_client, ref_int";
         $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
         $sql.= ", remise_absolue, remise_percent";
         $sql.= ", entity";
@@ -639,7 +640,7 @@ class Commande extends CommonOrder
         $sql.= ", ".($this->fk_project?$this->fk_project:"null");
         $sql.= ", ".$this->db->idate($date);
         $sql.= ", ".($this->source>=0 && $this->source != '' ?$this->source:'null');
-        $sql.= ", '".$this->db->escape($this->note)."'";
+        $sql.= ", '".$this->db->escape($this->note_private)."'";
         $sql.= ", '".$this->db->escape($this->note_public)."'";
         $sql.= ", '".$this->db->escape($this->ref_client)."'";
         $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
@@ -952,7 +953,7 @@ class Commande extends CommonOrder
             $this->fk_delivery_address  = $object->fk_delivery_address;
             $this->contact_id           = $object->contactid;
             $this->ref_client           = $object->ref_client;
-            $this->note                 = $object->note;
+            $this->note_private         = $object->note_private;
             $this->note_public          = $object->note_public;
 
             $this->origin				= $object->element;
@@ -1267,7 +1268,7 @@ class Commande extends CommonOrder
         $sql.= ', c.date_commande';
         $sql.= ', c.date_livraison';
         $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
-        $sql.= ', c.note as note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
+        $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams';
         $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
         $sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
         $sql.= ', ca.code as availability_code';
@@ -2697,7 +2698,7 @@ class Commande extends CommonOrder
         $this->availability_code   = 'DSP';
         $this->demand_reason_code  = 'SRC_00';
         $this->note_public='This is a comment (public)';
-        $this->note='This is a comment (private)';
+        $this->note_private='This is a comment (private)';
         // Lines
         $nbp = 5;
         $xnbp = 0;
@@ -2782,7 +2783,6 @@ class Commande extends CommonOrder
      *	Update value of extrafields on the proposal
      *
      *	@param      User	$user       Object user that modify
-     *	@param      double	$remise      Amount discount
      *	@return     int         		<0 if ko, >0 if ok
      */
     function update_extrafields($user)
diff --git a/htdocs/commande/fiche.php b/htdocs/commande/fiche.php
index 455eb698722605c58c08df6c4257fbb3d8dca7ae..ce25c5cab31899738c2ac95d5159bb50d1084fc6 100644
--- a/htdocs/commande/fiche.php
+++ b/htdocs/commande/fiche.php
@@ -45,6 +45,7 @@ if (! empty($conf->projet->enabled)) {
 	require DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 	require DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
 }
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 $langs->load('orders');
 $langs->load('sendings');
@@ -225,7 +226,7 @@ else if ($action == 'add' && $user->rights->commande->creer)
 		$db->begin();
 
 		$object->date_commande        = $datecommande;
-		$object->note                 = GETPOST('note');
+		$object->note_private         = GETPOST('note_private');
 		$object->note_public          = GETPOST('note_public');
 		$object->source               = GETPOST('source_id');
 		$object->fk_project           = GETPOST('projectid');
@@ -534,13 +535,13 @@ else if ($action == 'setremiseabsolue' && $user->rights->commande->creer)
 
 else if ($action == 'setnote_public' && $user->rights->commande->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->commande->creer)
+else if ($action == 'setnote_private' && $user->rights->commande->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note_rivate(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES));
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
@@ -1411,9 +1412,6 @@ $formorder = new FormOrder($db);
 *********************************************************************/
 if ($action == 'create' && $user->rights->commande->creer)
 {
-	//WYSIWYG Editor
-	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-
 	print_fiche_titre($langs->trans('CreateOrder'));
 
 	dol_htmloutput_mesg($mesg,$mesgs,'error');
@@ -1470,7 +1468,7 @@ if ($action == 'create' && $user->rights->commande->creer)
 
 			$datedelivery		= (!empty($objectsrc->date_livraison)?$objectsrc->date_livraison:'');
 
-			$note_private		= (! empty($objectsrc->note) ? $objectsrc->note : (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''));
+			$note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''));
 			$note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
 
 			// Object source contacts list
@@ -1632,7 +1630,7 @@ if ($action == 'create' && $user->rights->commande->creer)
 		print '<td class="border" valign="top">'.$langs->trans('NotePrivate').'</td>';
 		print '<td valign="top" colspan="2">';
 
-		$doleditor=new DolEditor('note', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+		$doleditor=new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
 		print $doleditor->Create(1);
 		//print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
 		print '</td></tr>';
diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php
index 194d7f5e91c25ccb1de66df10ef21fa0e9f3b572..c9ca34854b7170d9b9733238561e63c272ec1a68 100644
--- a/htdocs/commande/note.php
+++ b/htdocs/commande/note.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
  * Copyright (C) 2004-2007 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -57,14 +58,14 @@ if (! $object->fetch($id, $ref) > 0)
 if ($action == 'setnote_public' && $user->rights->commande->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->commande->creer)
+else if ($action == 'setnote_private' && $user->rights->commande->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/compta/deplacement/class/deplacement.class.php b/htdocs/compta/deplacement/class/deplacement.class.php
index 1c8820cbd2b850ff47b7d13ebc9d3692d9ea0005..66644cde84869db1906a266e6fbf51ad14872320 100644
--- a/htdocs/compta/deplacement/class/deplacement.class.php
+++ b/htdocs/compta/deplacement/class/deplacement.class.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2003		Rodolphe Quiedeville	<rodolphe@quiedeville.org>
  * Copyright (C) 2004-2011	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2009-2012	Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -101,7 +102,7 @@ class Deplacement extends CommonObject
 		$sql.= ", fk_user_author";
 		$sql.= ", fk_user";
 		$sql.= ", type";
-		$sql.= ", note";
+		$sql.= ", note_private";
 		$sql.= ", note_public";
 		$sql.= ", fk_projet";
 		$sql.= ", fk_soc";
@@ -195,7 +196,7 @@ class Deplacement extends CommonObject
 		$sql .= " , fk_user = ".$this->fk_user;
 		$sql .= " , fk_user_modif = ".$user->id;
 		$sql .= " , fk_soc = ".($this->socid > 0?$this->socid:'null');
-		$sql .= " , note = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
+		$sql .= " , note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null");
 		$sql .= " , note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
 		$sql .= " , fk_projet = ".($this->fk_project>0?$this->fk_project:0);
 		$sql .= " WHERE rowid = ".$this->id;
@@ -223,7 +224,7 @@ class Deplacement extends CommonObject
 	*/
 	function fetch($id)
 	{
-		$sql = "SELECT rowid, fk_user, type, fk_statut, km, fk_soc, dated, note, note_public, fk_projet, extraparams";
+		$sql = "SELECT rowid, fk_user, type, fk_statut, km, fk_soc, dated, note_private, note_public, fk_projet, extraparams";
 		$sql.= " FROM ".MAIN_DB_PREFIX."deplacement";
 		$sql.= " WHERE rowid = ".$id;
 
@@ -241,7 +242,7 @@ class Deplacement extends CommonObject
 			$this->km			= $obj->km;
 			$this->type			= $obj->type;
 			$this->statut	    = $obj->fk_statut;
-			$this->note_private	= $obj->note;
+			$this->note_private	= $obj->note_private;
 			$this->note_public	= $obj->note_public;
 			$this->fk_project	= $obj->fk_projet;
 
diff --git a/htdocs/compta/deplacement/fiche.php b/htdocs/compta/deplacement/fiche.php
index 1e20d91c3500a7989bdd9325a6d32b638f8efaa2..b09754c2405a11e106366b1ecda770aeb84ca849 100644
--- a/htdocs/compta/deplacement/fiche.php
+++ b/htdocs/compta/deplacement/fiche.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2012	Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2012		Juanjo Menent        <jmenent@2byte.es>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -234,13 +235,13 @@ else if ($action == 'setkm' && $user->rights->deplacement->creer)
 else if ($action == 'setnote_public' && $user->rights->deplacement->creer)
 {
     $object->fetch($id);
-    $result=$object->setValueFrom('note_public',GETPOST('note_public','alpha'));
+    $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
     if ($result < 0) dol_print_error($db, $object->error);
 }
-else if ($action == 'setnote' && $user->rights->deplacement->creer)
+else if ($action == 'setnote_private' && $user->rights->deplacement->creer)
 {
     $object->fetch($id);
-    $result=$object->setValueFrom('note',GETPOST('note','alpha'));
+    $result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
     if ($result < 0) dol_print_error($db, $object->error);
 }
 
diff --git a/htdocs/compta/dons/class/don.class.php b/htdocs/compta/dons/class/don.class.php
index 9ca97617db6fd453195318e0f5881155ccdb39d2..f5d477de48ffb313fa4b3102f09eaaf92bef810f 100644
--- a/htdocs/compta/dons/class/don.class.php
+++ b/htdocs/compta/dons/class/don.class.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2002      Rodolphe Quiedeville <rodolphe@quiedeville.org>
  * Copyright (C) 2004-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2009      Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -51,7 +52,8 @@ class Don extends CommonObject
     var $fk_project;
     var $modepaiement;
     var $modepaiementid;
-    var $note;
+    var $note_private;
+    var $note_public;
     var $statut;
 
     var $projet;
@@ -191,7 +193,8 @@ class Don extends CommonObject
         $this->address = 'Twist road';
         $this->zip = '99999';
         $this->town = 'Town';
-        $this->note_public='SPECIMEN';
+        $this->note_private='Private note';
+        $this->note_public='Public note';
         $this->email='email@email.com';
         $this->note='';
         $this->statut=1;
@@ -319,7 +322,8 @@ class Don extends CommonObject
         $sql.= ", country";
         $sql.= ", public";
         $sql.= ", fk_don_projet";
-        $sql.= ", note";
+        $sql.= ", note_private";
+        $sql.= ", note_public";
         $sql.= ", fk_user_author";
         $sql.= ", fk_user_valid";
         $sql.= ", datedon";
@@ -340,7 +344,8 @@ class Don extends CommonObject
         $sql.= ", '".$this->db->escape($this->country)."'"; // TODO use country_id
         $sql.= ", ".$this->public;
         $sql.= ", ".($this->fk_project > 0?$this->fk_project:"null");
-        $sql.= ", '".$this->db->escape($this->note)."'";
+       	$sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
+		$sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
         $sql.= ", ".$user->id;
         $sql.= ", null";
         $sql.= ", '".$this->db->idate($this->date)."'";
@@ -400,7 +405,8 @@ class Don extends CommonObject
         $sql .= ",country='".$this->db->escape($this->country)."'"; // TODO use country_id
         $sql .= ",public=".$this->public;
         $sql .= ",fk_don_projet=".($this->fk_project>0?$this->fk_project:'null');
-        $sql .= ",note='".$this->db->escape($this->note)."'";
+        $sql .= ",note_private=".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
+        $sql .= ",note_public=".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
         $sql .= ",datedon='".$this->db->idate($this->date)."'";
         $sql .= ",email='".$this->email."'";
         $sql .= ",phone='".$this->phone."'";
@@ -463,7 +469,9 @@ class Don extends CommonObject
         global $conf;
 
         $sql = "SELECT d.rowid, d.datec, d.tms as datem, d.datedon,";
-        $sql.= " d.firstname, d.lastname, d.societe, d.amount, d.fk_statut, d.address, d.zip, d.town, d.country, d.public, d.amount, d.fk_paiement, d.note, cp.libelle, d.email, d.phone, d.phone_mobile, d.fk_don_projet,";
+        $sql.= " d.firstname, d.lastname, d.societe, d.amount, d.fk_statut, d.address, d.zip, d.town, ";
+        $sql.= " 	d.country, d.public, d.amount, d.fk_paiement, d.note_private, d.note_public, cp.libelle, d.email, d.phone, ";
+        $sql.= " 	d.phone_mobile, d.fk_don_projet,";
         $sql.= " p.title as project_label";
         $sql.= " FROM ".MAIN_DB_PREFIX."don as d";
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_don_projet";
@@ -501,7 +509,8 @@ class Don extends CommonObject
                 $this->modepaiementid = $obj->fk_paiement;
                 $this->modepaiement   = $obj->libelle;
                 $this->amount         = $obj->amount;
-                $this->note			  = $obj->note;
+                $this->note_private	  = $obj->note_private;
+                $this->note_public	  = $obj->note_public;
                 $this->commentaire    = $obj->note;	// deprecated
             }
             return 1;
diff --git a/htdocs/compta/dons/fiche.php b/htdocs/compta/dons/fiche.php
index 8c916b7c5f29e2320384bd92c1f07cebf6ac17c1..e04c6699848f1c088f2e99c936c3702e4bb9ebe0 100644
--- a/htdocs/compta/dons/fiche.php
+++ b/htdocs/compta/dons/fiche.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2001-2002	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
  * Copyright (C) 2004-2011	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -98,7 +99,8 @@ if ($action == 'update')
 		$don->note        = $_POST["note"];
 		$don->public      = $_POST["public"];
 		$don->fk_project  = $_POST["projectid"];
-		$don->note        = $_POST["comment"];
+		$don->note_private= GETPOST("note_private");
+		$don->note_public = GETPOST("note_public");
 		$don->modepaiementid = $_POST["modepaiement"];
 
 		if ($don->update($user) > 0)
@@ -146,10 +148,10 @@ if ($action == 'add')
         $don->country     = $_POST["country"];
 		$don->email       = $_POST["email"];
 		$don->date        = $donation_date;
-		$don->note        = $_POST["note"];
+		$don->note_private= GETPOST("note_private");
+		$don->note_public = GETPOST("note_public");
 		$don->public      = $_POST["public"];
 		$don->fk_project  = $_POST["projectid"];
-		$don->note        = $_POST["comment"];
 		$don->modepaiementid = $_POST["modepaiement"];
 
 		if ($don->create($user) > 0)
@@ -283,7 +285,7 @@ if ($action == 'create')
 	print '</td>';
 
     print '<td rowspan="'.$nbrows.'" valign="top">'.$langs->trans("Comments").' :<br>';
-    print "<textarea name=\"comment\" wrap=\"soft\" cols=\"40\" rows=\"15\">".$_POST["comment"]."</textarea></td>";
+    print "<textarea name=\"note_private\" wrap=\"soft\" cols=\"40\" rows=\"15\">".GETPOST("note_private")."</textarea></td>";
     print "</tr>";
 
     // Amount
@@ -371,7 +373,7 @@ if (! empty($id) && $action == 'edit')
 	print '</td>';
 
     print '<td rowspan="'.$nbrows.'" valign="top">'.$langs->trans("Comments").' :<br>';
-    print "<textarea name=\"comment\" wrap=\"soft\" cols=\"40\" rows=\"15\">".$don->note."</textarea></td>";
+    print "<textarea name=\"note_private\" wrap=\"soft\" cols=\"40\" rows=\"15\">".$don->note_private."</textarea></td>";
     print "</tr>";
 
 	// Amount
@@ -471,7 +473,7 @@ if (! empty($id) && $action != 'edit')
 	print "</td>";
 
     print '<td rowspan="'.$nbrows.'" valign="top" width="50%">'.$langs->trans("Comments").' :<br>';
-	print nl2br($don->note).'</td></tr>';
+	print nl2br($don->note_private).'</td></tr>';
 
     print "<tr>".'<td>'.$langs->trans("Amount").'</td><td>'.price($don->amount).' '.$langs->trans("Currency".$conf->currency).'</td></tr>';
 
diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php
index e4b7e923ef05bd0b2cf7fa076ef97604a76aeb6f..4c85064e427a0f3603c937ad44bbc22235c31cf4 100644
--- a/htdocs/compta/facture.php
+++ b/htdocs/compta/facture.php
@@ -8,6 +8,7 @@
  * Copyright (C) 2010-2013 Juanjo Menent         <jmenent@2byte.es>
  * Copyright (C) 2012      Christophe Battarel   <christophe.battarel@altairis.fr>
  * Copyright (C) 2013      Jean-Francois FERRY   <jfefe@aternatik.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -43,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
 if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
 if (! empty($conf->projet->enabled))   require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
 if (! empty($conf->projet->enabled))   require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 $langs->load('bills');
 $langs->load('companies');
@@ -351,14 +353,14 @@ else if ($action == 'set_ref_client' && $user->rights->facture->creer)
 else if ($action == 'setnote_public' && $user->rights->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->facture->creer)
+else if ($action == 'setnote_private' && $user->rights->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
@@ -695,7 +697,7 @@ else if ($action == 'add' && $user->rights->facture->creer)
 
             //$result=$object->fetch($_POST['fac_avoir']);
 
-            $object->socid				= $_POST['socid'];
+            $object->socid				= GETPOST('socid','int');
             $object->number				= $_POST['facnumber'];
             $object->date				= $datefacture;
             $object->note_public		= trim($_POST['note_public']);
@@ -742,12 +744,12 @@ else if ($action == 'add' && $user->rights->facture->creer)
 
         if (! $error)
         {
-            $object->socid			= $_POST['socid'];
+            $object->socid			= GETPOST('socid','int');
             $object->type           = $_POST['type'];
             $object->number         = $_POST['facnumber'];
             $object->date           = $datefacture;
             $object->note_public	= trim($_POST['note_public']);
-            $object->note           = trim($_POST['note']);
+            $object->note_private   = trim($_POST['note_private']);
             $object->ref_client     = $_POST['ref_client'];
             $object->ref_int     	= $_POST['ref_int'];
             $object->modelpdf       = $_POST['model'];
@@ -778,12 +780,12 @@ else if ($action == 'add' && $user->rights->facture->creer)
         if (! $error)
         {
             // Si facture standard
-            $object->socid				= $_POST['socid'];
-            $object->type				= $_POST['type'];
+            $object->socid				= GETPOST('socid','int');
+            $object->type				= GETPOST('type');
             $object->number				= $_POST['facnumber'];
             $object->date				= $datefacture;
             $object->note_public		= trim($_POST['note_public']);
-            $object->note				= trim($_POST['note']);
+            $object->note_private		= trim($_POST['note_private']);
             $object->ref_client			= $_POST['ref_client'];
             $object->ref_int			= $_POST['ref_int'];
             $object->modelpdf			= $_POST['model'];
@@ -2113,12 +2115,15 @@ if ($action == 'create')
     print '<tr>';
     print '<td class="border" valign="top">'.$langs->trans('NotePublic').'</td>';
     print '<td valign="top" colspan="2">';
-    print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">';
+    $note_public='';
     if (is_object($objectsrc))    // Take value from source object
     {
-        print $objectsrc->note_public;
+    	$note_public=$objectsrc->note_public;
     }
-    print '</textarea></td></tr>';
+    $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+    print $doleditor->Create(1);
+    
+    //print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea></td></tr>';
 
     // Private note
     if (empty($user->societe_id))
@@ -2126,12 +2131,14 @@ if ($action == 'create')
         print '<tr>';
         print '<td class="border" valign="top">'.$langs->trans('NotePrivate').'</td>';
         print '<td valign="top" colspan="2">';
-        print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">';
+        $note_private='';
         if (! empty($origin) && ! empty($originid) && is_object($objectsrc))    // Take value from source object
         {
-            print $objectsrc->note;
+        	$note_private=$objectsrc->note_private;
         }
-        print '</textarea></td></tr>';
+        $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+        print $doleditor->Create(1);
+        //print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea></td></tr>';
     }
 
     if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php
index 4e168d0645f5c5c83563fa940f62c9414c58d6b5..1651407d746b9122ec639fac449f7a972ed085bc 100644
--- a/htdocs/compta/facture/class/facture-rec.class.php
+++ b/htdocs/compta/facture/class/facture-rec.class.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2012	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2009-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2010-2011	Juanjo Menent			<jmenent@2byte.es>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -54,7 +55,8 @@ class FactureRec extends Facture
 	var $remise;
 	var $tva;
 	var $total;
-	var $note;
+	var $note_private;
+	var $note_public;
 	var $db_table;
 	var $propalid;
 	var $fk_project;
@@ -111,7 +113,8 @@ class FactureRec extends Facture
 			$sql.= ", datec";
 			$sql.= ", amount";
 			$sql.= ", remise";
-			$sql.= ", note";
+			$sql.= ", note_private";
+			$sql.= ", note_public";
 			$sql.= ", fk_user_author";
 			$sql.= ", fk_projet";
 			$sql.= ", fk_cond_reglement";
@@ -124,7 +127,8 @@ class FactureRec extends Facture
 			$sql.= ", ".$this->db->idate($now);
 			$sql.= ", '".$facsrc->amount."'";
 			$sql.= ", '".$facsrc->remise."'";
-			$sql.= ", '".$this->db->escape($this->note)."'";
+			$sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
+			$sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
 			$sql.= ", '".$user->id."'";
 			$sql.= ", ".(! empty($facsrc->fk_project)?"'".$facsrc->fk_project."'":"null");
 			$sql.= ", '".$facsrc->cond_reglement_id."'";
@@ -201,7 +205,7 @@ class FactureRec extends Facture
 	{
 		$sql = 'SELECT f.titre,f.fk_soc,f.amount,f.tva,f.total,f.total_ttc,f.remise_percent,f.remise_absolue,f.remise';
 		$sql.= ', f.date_lim_reglement as dlr';
-		$sql.= ', f.note, f.note_public, f.fk_user_author';
+		$sql.= ', f.note_private, f.note_public, f.fk_user_author';
 		$sql.= ', f.fk_mode_reglement, f.fk_cond_reglement';
 		$sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
 		$sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
@@ -249,7 +253,7 @@ class FactureRec extends Facture
 				$this->cond_reglement_doc     = $obj->cond_reglement_libelle_doc;
 				$this->fk_project             = $obj->fk_projet;
 				$this->fk_facture_source      = $obj->fk_facture_source;
-				$this->note                   = $obj->note;
+				$this->note_private           = $obj->note_private;
 				$this->note_public            = $obj->note_public;
 				$this->user_author            = $obj->fk_user_author;
 				$this->modelpdf               = $obj->model_pdf;
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index 6c19894e7f1853fe90ca6e90f30903bfabc2eb99..f4dc4527c746f8d3dfc36d1dd6e0cbdf19b8bc3c 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -11,6 +11,7 @@
  * Copyright (C) 2012      Christophe Battarel   <christophe.battarel@altairis.fr>
  * Copyright (C) 2012      Marcos García         <marcosgdf@gmail.com>
  * Copyright (C) 2013      Cedric Gross          <c.gross@kreiz-it.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -144,7 +145,7 @@ class Facture extends CommonInvoice
         if (empty($this->type)) $this->type = 0;
         $this->ref_client=trim($this->ref_client);
         $this->note=(isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
-        $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note));
+        $this->note_private=(isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
         $this->note_public=trim($this->note_public);
         if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
         if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
@@ -190,7 +191,7 @@ class Facture extends CommonInvoice
             // Clean parametres
             if (! $this->type) $this->type = 0;
             $this->ref_client=trim($this->ref_client);
-            $this->note=trim($this->note);
+            $this->note_private=trim($this->note_private);
             $this->note_public=trim($this->note_public);
             //if (! $this->remise) $this->remise = 0;
             if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
@@ -213,7 +214,7 @@ class Facture extends CommonInvoice
         $sql.= ", remise_absolue";
         $sql.= ", remise_percent";
         $sql.= ", datef";
-        $sql.= ", note";
+        $sql.= ", note_private";
         $sql.= ", note_public";
         $sql.= ", ref_client, ref_int";
         $sql.= ", fk_facture_source, fk_user_author, fk_projet";
@@ -516,7 +517,7 @@ class Facture extends CommonInvoice
         $facture->socid 		    = $this->socid;
         $facture->date              = $this->date;
         $facture->note_public       = $this->note_public;
-        $facture->note              = $this->note;
+        $facture->note_private      = $this->note_private;
         $facture->ref_client        = $this->ref_client;
         $facture->modelpdf          = $this->modelpdf;
         $facture->fk_project        = $this->fk_project;
@@ -703,7 +704,7 @@ class Facture extends CommonInvoice
         $this->fk_delivery_address  = $object->fk_delivery_address;
         $this->contact_id           = $object->contactid;
         $this->ref_client           = $object->ref_client;
-        $this->note                 = $object->note;
+        $this->note_private         = $object->note_private;
         $this->note_public          = $object->note_public;
 
         $this->origin				= $object->element;
@@ -802,7 +803,7 @@ class Facture extends CommonInvoice
         $sql.= ', f.datec as datec';
         $sql.= ', f.date_valid as datev';
         $sql.= ', f.tms as datem';
-        $sql.= ', f.note as note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
+        $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
         $sql.= ', f.fk_facture_source';
         $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams';
         $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
@@ -1061,7 +1062,7 @@ class Facture extends CommonInvoice
         $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
         $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
         $sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
-        $sql.= " note=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
+        $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
         $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
         $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
         $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php
index 804c34cf7019ba34c334d3541a522b97e0f6f26e..54d0c8009203932a05bb48b159f9dcf6a216a54c 100644
--- a/htdocs/compta/facture/fiche-rec.php
+++ b/htdocs/compta/facture/fiche-rec.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  * Copyright (C) 2004-2012 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -72,7 +73,7 @@ if ($action == 'add')
 	if (! $error)
 	{
 		$object->titre = GETPOST('titre', 'alpha');
-		$object->note  = GETPOST('note');
+		$object->note_private  = GETPOST('note_private');
 		$object->usenewprice = GETPOST('usenewprice');
 
 		if ($object->create($user, $id) > 0)
@@ -143,7 +144,7 @@ if ($action == 'create')
 
 		// Note
 		print '<td rowspan="'.$rowspan.'" valign="top">';
-		print '<textarea class="flat" name="note" wrap="soft" cols="60" rows="'.ROWS_4.'"></textarea>';
+		print '<textarea class="flat" name="note_private" wrap="soft" cols="60" rows="'.ROWS_4.'"></textarea>';
 		print '</td></tr>';
 
 		// Author
@@ -394,7 +395,7 @@ else
 			$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id,'none');
 			print "</td></tr>";
 
-			print '<tr><td>'.$langs->trans("Note").'</td><td colspan="3">'.nl2br($object->note)."</td></tr>";
+			print '<tr><td>'.$langs->trans("Note").'</td><td colspan="3">'.nl2br($object->note_private)."</td></tr>";
 
 			print "</table>";
 
diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php
index 796bf7696986afc5a1a931a499943f878d1f6f14..1003dd2370093f30bd0eac56eee97d7f61b105b0 100644
--- a/htdocs/compta/facture/list.php
+++ b/htdocs/compta/facture/list.php
@@ -7,6 +7,7 @@
  * Copyright (C) 2006      Andre Cianfarani      <acianfa@free.fr>
  * Copyright (C) 2010-2012 Juanjo Menent         <jmenent@2byte.es>
  * Copyright (C) 2012      Christophe Battarel   <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -140,7 +141,7 @@ if (! $sall) $sql = 'SELECT';
 else $sql = 'SELECT DISTINCT';
 $sql.= ' f.rowid as facid, f.facnumber, f.type, f.increment, f.total as total_ht, f.tva as total_tva, f.total_ttc,';
 $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,';
-$sql.= ' f.paye as paye, f.fk_statut, f.note,';
+$sql.= ' f.paye as paye, f.fk_statut,';
 $sql.= ' s.nom, s.rowid as socid';
 if (! $sall) $sql.= ', SUM(pf.amount) as am';   // To be able to sort on status
 $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
@@ -210,7 +211,7 @@ if (! $sall)
 {
     $sql.= ' GROUP BY f.rowid, f.facnumber, f.type, f.increment, f.total, f.total_ttc,';
     $sql.= ' f.datef, f.date_lim_reglement,';
-    $sql.= ' f.paye, f.fk_statut, f.note,';
+    $sql.= ' f.paye, f.fk_statut,';
     $sql.= ' s.nom, s.rowid';
 }
 else
diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php
index a96f5643b803c49f0c3295f1e03f1e09a5999043..6092ba39e85d309a999d5c3d2fedb95c766f245c 100644
--- a/htdocs/compta/facture/note.php
+++ b/htdocs/compta/facture/note.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
  * Copyright (C) 2004-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -52,14 +53,14 @@ $object->fetch($id);
 if ($action == 'setnote_public' && $user->rights->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->facture->creer)
+else if ($action == 'setnote_private' && $user->rights->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php
index 73bdbc4a0f4e530017e65330073225f222b70e20..a41aaf6b366a6d4b6db4e4dfe63f30d0c232d3c5 100644
--- a/htdocs/contact/class/contact.class.php
+++ b/htdocs/contact/class/contact.class.php
@@ -5,6 +5,7 @@
  * Copyright (C) 2005-2012 Regis Houssin               <regis.houssin@capnetworks.com>
  * Copyright (C) 2007      Franky Van Liedekerke       <franky.van.liedekerker@telenet.be>
  * Copyright (C) 2008      Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -63,7 +64,8 @@ class Contact extends CommonObject
 	var $birthday;
 	var $default_lang;
     var $note_public;           // Public note
-	var $note;                  // Private note
+	var $note;                  // deprecated
+	var $note_private;			// Private note
     var $no_email;				// 1=Don't send e-mail to this contact, 0=do
 
 	var $ref_facturation;       // Nb de reference facture pour lequel il est contact
@@ -238,7 +240,8 @@ class Contact extends CommonObject
 		$sql .= ", poste='".$this->db->escape($this->poste)."'";
 		$sql .= ", fax='".$this->db->escape($this->fax)."'";
 		$sql .= ", email='".$this->db->escape($this->email)."'";
-		$sql .= ", note='".$this->db->escape($this->note)."'";
+		$sql .= ", note_private='".$this->db->escape($this->note_private)."'";
+		$sql .= ", note_public='".$this->db->escape($this->note_public)."'";
 		$sql .= ", phone = '".$this->db->escape($this->phone_pro)."'";
 		$sql .= ", phone_perso = '".$this->db->escape($this->phone_perso)."'";
 		$sql .= ", phone_mobile = '".$this->db->escape($this->phone_mobile)."'";
@@ -366,7 +369,7 @@ class Contact extends CommonObject
 		if ($this->phone_perso && ! empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
 		if ($this->phone_mobile && ! empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
 		if ($this->fax && ! empty($conf->global->LDAP_CONTACT_FIELD_FAX))	    $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
-		if ($this->note && ! empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = $this->note;
+		if ($this->note_private && ! empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = $this->note_private;
 		if ($this->email && ! empty($conf->global->LDAP_CONTACT_FIELD_MAIL))     $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
 
 		if ($conf->global->LDAP_SERVER_TYPE == 'egroupware')
@@ -482,7 +485,7 @@ class Contact extends CommonObject
 		$sql.= " c.fk_departement,";
 		$sql.= " c.birthday,";
 		$sql.= " c.poste, c.phone, c.phone_perso, c.phone_mobile, c.fax, c.email, c.jabberid,";
-		$sql.= " c.priv, c.note, c.default_lang, c.no_email, c.canvas,";
+		$sql.= " c.priv, c.note_private, c.note_public, c.default_lang, c.no_email, c.canvas,";
 		$sql.= " c.import_key,";
 		$sql.= " p.libelle as country, p.code as country_code,";
 		$sql.= " d.nom as state, d.code_departement as state_code,";
@@ -538,7 +541,9 @@ class Contact extends CommonObject
 				$this->mail				= $obj->email;
 
 				$this->birthday			= $this->db->jdate($obj->birthday);
-				$this->note				= $obj->note;
+				$this->note				= $obj->note_private;		// deprecated
+				$this->note_private		= $obj->note_private;
+				$this->note_public		= $obj->note_public;
 				$this->default_lang		= $obj->default_lang;
 				$this->no_email			= $obj->no_email;
 				$this->user_id			= $obj->user_id;
@@ -1008,7 +1013,7 @@ class Contact extends CommonObject
 		$this->fax = '0909090909';
 
 		$this->note_public='This is a comment (public)';
-		$this->note='This is a comment (private)';
+		$this->note_private='This is a comment (private)';
 
 		$socid = rand(1, $num_socs);
 		$this->socid = $socids[$socid];
diff --git a/htdocs/contact/fiche.php b/htdocs/contact/fiche.php
index db0fe091cd9e3c6d8a42cc826f2c9d78b1fa0de9..9711654fa0314bd6e9b0670221c25d79b7161d23 100644
--- a/htdocs/contact/fiche.php
+++ b/htdocs/contact/fiche.php
@@ -4,6 +4,7 @@
  * Copyright (C) 2004      Benoit Mortier       <benoit.mortier@opensides.be>
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -32,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 $langs->load("companies");
 $langs->load("users");
@@ -152,14 +154,15 @@ if (empty($reshook))
         $object->jabberid		= $_POST["jabberid"];
 		$object->no_email		= $_POST["no_email"];
         $object->priv			= $_POST["priv"];
-        $object->note			= $_POST["note"];
+        $object->note_public	= GETPOST("note_public");
+        $object->note_private	= GETPOST("note_private");
 
         // Note: Correct date should be completed with location to have exact GM time of birth.
         $object->birthday = dol_mktime(0,0,0,$_POST["birthdaymonth"],$_POST["birthdayday"],$_POST["birthdayyear"]);
         $object->birthday_alert = $_POST["birthday_alert"];
 
         // Fill array 'array_options' with data from add form
-		$ret = $extrafields->setOptionalsFromPost($extralabels,$object); 
+		$ret = $extrafields->setOptionalsFromPost($extralabels,$object);
 
         if (! $_POST["lastname"])
         {
@@ -247,10 +250,11 @@ if (empty($reshook))
             $object->jabberid		= $_POST["jabberid"];
 			$object->no_email		= $_POST["no_email"];
             $object->priv			= $_POST["priv"];
-            $object->note			= $_POST["note"];
+        	$object->note_public	= GETPOST("note_public");
+       		$object->note_private	= GETPOST("note_private");
 
             // Fill array 'array_options' with data from add form
-			$ret = $extrafields->setOptionalsFromPost($extralabels,$object); 
+			$ret = $extrafields->setOptionalsFromPost($extralabels,$object);
 
             $result = $object->update($_POST["contactid"], $user);
 
@@ -296,11 +300,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
     // -----------------------------------------
     if (empty($object->error) && $id)
  	{
-	     $object = new Contact($db);
-	     $object->fetch($id);
+ 		$object = new Contact($db);
+ 		$result=$object->fetch($id);
+		if ($result <= 0) dol_print_error('',$object->error);
  	}
-	$objcanvas->assign_values($action, $id);	// Set value for templates
-	$objcanvas->display_canvas($action);		// Show template
+   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
+    $objcanvas->display_canvas($action);							// Show template
 }
 else
 {
@@ -499,8 +504,21 @@ else
             print $form->selectarray('priv',$selectarray,(isset($_POST["priv"])?$_POST["priv"]:$object->priv),0);
             print '</td></tr>';
 
-            // Note
-            print '<tr><td valign="top">'.$langs->trans("Note").'</td><td colspan="3" valign="top"><textarea name="note" cols="70" rows="'.ROWS_3.'">'.(isset($_POST["note"])?$_POST["note"]:$object->note).'</textarea></td></tr>';
+            // Note Public
+            print '<tr><td valign="top">'.$langs->trans("NotePublic").'</td>';
+            print '<td colspan="3" valign="top">';
+            $doleditor = new DolEditor('note_public', GETPOST('note_public'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);
+            //print '<textarea name="note" cols="70" rows="'.ROWS_3.'">'.(isset($_POST["note"])?$_POST["note"]:$object->note).'</textarea>';
+            print '</td></tr>';
+
+            // Note Private
+            print '<tr><td valign="top">'.$langs->trans("NotePrivate").'</td>';
+            print '<td colspan="3" valign="top">';
+            $doleditor = new DolEditor('note_private', GETPOST('note_private'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);
+            //print '<textarea name="note" cols="70" rows="'.ROWS_3.'">'.(isset($_POST["note"])?$_POST["note"]:$object->note).'</textarea>';
+            print '</td></tr>';
 
             // Other attributes
             $parameters=array('colspan' => ' colspan="3"');
@@ -703,11 +721,23 @@ else
             print $form->selectarray('priv',$selectarray,$object->priv,0);
             print '</td></tr>';
 
-            // Note
-            print '<tr><td valign="top">'.$langs->trans("Note").'</td><td colspan="3">';
-            print '<textarea name="note" cols="70" rows="'.ROWS_3.'">';
-            print isset($_POST["note"])?$_POST["note"]:$object->note;
-            print '</textarea></td></tr>';
+            // Note Public
+            print '<tr><td valign="top">'.$langs->trans("NotePublic").'</td><td colspan="3">';
+            $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);
+           // print '<textarea name="note" cols="70" rows="'.ROWS_3.'">';
+           // print isset($_POST["note"])?$_POST["note"]:$object->note;
+           // print '</textarea></td></tr>';
+           print '</td></tr>';
+
+           // Note Private
+           print '<tr><td valign="top">'.$langs->trans("NotePrivate").'</td><td colspan="3">';
+           $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+           print $doleditor->Create(1);
+           // print '<textarea name="note" cols="70" rows="'.ROWS_3.'">';
+           // print isset($_POST["note"])?$_POST["note"]:$object->note;
+           // print '</textarea></td></tr>';
+           print '</td></tr>';
 
             // Other attributes
             $parameters=array('colspan' => ' colspan="3"');
@@ -908,9 +938,14 @@ else
         print $object->LibPubPriv($object->priv);
         print '</td></tr>';
 
-        // Note
-        print '<tr><td valign="top">'.$langs->trans("Note").'</td><td colspan="3">';
-        print nl2br($object->note);
+        // Note Public
+        print '<tr><td valign="top">'.$langs->trans("NotePublic").'</td><td colspan="3">';
+        print nl2br($object->note_public);
+        print '</td></tr>';
+
+        // Note Private
+        print '<tr><td valign="top">'.$langs->trans("NotePrivate").'</td><td colspan="3">';
+        print nl2br($object->note_private);
         print '</td></tr>';
 
         // Other attributes
diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php
index d85b8fb89b1b9ee4ceb2194f275a911fd143fd86..afbc82ab39108f071c9d4d9b091484a2240fd2fa 100644
--- a/htdocs/contrat/class/contrat.class.php
+++ b/htdocs/contrat/class/contrat.class.php
@@ -5,7 +5,8 @@
  * Copyright (C) 2006		Andre Cianfarani		<acianfa@free.fr>
  * Copyright (C) 2008		Raphael Bertrand		<raphael.bertrand@resultic.fr>
  * Copyright (C) 2010-2011	Juanjo Menent			<jmenent@2byte.es>
- * Copyright (C) 2013     Christophe Battarel  <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013       Christophe Battarel  <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -338,7 +339,7 @@ class Contrat extends CommonObject
 		$sql.= " fk_user_author,";
 		$sql.= " fk_projet,";
 		$sql.= " fk_commercial_signature, fk_commercial_suivi,";
-		$sql.= " note as note_private, note_public, extraparams";
+		$sql.= " note_private, note_public, extraparams";
 		$sql.= " FROM ".MAIN_DB_PREFIX."contrat";
 		if ($ref)
 		{
@@ -649,7 +650,7 @@ class Contrat extends CommonObject
 		// Insert contract
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
 		$sql.= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
-		$sql.= " ref, entity, note, note_public)";
+		$sql.= " ref, entity, note_private, note_public)";
 		$sql.= " VALUES (".$this->db->idate($now).",".$this->socid.",".$user->id;
 		$sql.= ",".$this->db->idate($this->date_contrat);
 		$sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL");
@@ -657,7 +658,7 @@ class Contrat extends CommonObject
 		$sql.= ",".($this->fk_project>0?$this->fk_project:"NULL");
 		$sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->ref."'");
 		$sql.= ", ".$conf->entity;
-		$sql.= ", ".(!empty($this->note)?("'".$this->db->escape($this->note)."'"):"NULL");
+		$sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
 		$sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
 		$sql.= ")";
 		$resql=$this->db->query($sql);
@@ -1605,8 +1606,8 @@ class Contrat extends CommonObject
 		$this->date_contrat = dol_now();
 		$this->commercial_signature_id = 1;
 		$this->commercial_suivi_id = 1;
-		$this->note='This is a comment (private)';
-		$this->note='This is a comment (public)';
+		$this->note_private='This is a comment (private)';
+		$this->note_public='This is a comment (public)';
 		$this->fk_projet = 0;
 		// Lines
 		$nbp = 5;
diff --git a/htdocs/contrat/fiche.php b/htdocs/contrat/fiche.php
index f0fd4cd66ea66c648d619b08d8800d0ad6a938ac..d3ef925158bcfd48ca9407318144b4d5f95ffab8 100644
--- a/htdocs/contrat/fiche.php
+++ b/htdocs/contrat/fiche.php
@@ -4,7 +4,8 @@
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2006		Andre Cianfarani		<acianfa@free.fr>
  * Copyright (C) 2010-2012	Juanjo Menent			<jmenent@2byte.es>
- * Copyright (C) 2013      Christophe Battarel   <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013       Christophe Battarel   <christophe.battarel@altairis.fr>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -32,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 if (! empty($conf->produit->enabled) || ! empty($conf->service->enabled))  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 if (! empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
 if (! empty($conf->projet->enabled)) {
@@ -182,7 +184,7 @@ if ($action == 'add' && $user->rights->contrat->creer)
     	$object->commercial_suivi_id		= GETPOST('commercial_suivi_id','int');
     	$object->commercial_signature_id	= GETPOST('commercial_signature_id','int');
 
-    	$object->note						= GETPOST('note','alpha');
+    	$object->note_private				= GETPOST('note_private','alpha');
     	$object->note_public				= GETPOST('note_public','alpha');
     	$object->fk_project					= GETPOST('projectid','int');
     	$object->remise_percent				= GETPOST('remise_percent','alpha');
@@ -656,13 +658,13 @@ else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contra
 
 else if ($action == 'setnote_public' && $user->rights->contrat->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->contrat->creer)
+else if ($action == 'setnote_private' && $user->rights->contrat->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
@@ -785,7 +787,7 @@ if ($action == 'create')
 
             $soc = $objectsrc->client;
 
-            $note_private		= (! empty($objectsrc->note) ? $objectsrc->note : (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''));
+            $note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : '');
             $note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
 
             // Object source contacts list
@@ -794,7 +796,7 @@ if ($action == 'create')
     }
     else {
 		$projectid = GETPOST('projectid','int');
-		$note_private = GETPOST("note");
+		$note_private = GETPOST("note_private");
 		$note_public = GETPOST("note_public");
 	}
 
@@ -869,25 +871,16 @@ if ($action == 'create')
 
     print '<tr><td>'.$langs->trans("NotePublic").'</td><td valign="top">';
 
-    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+    
     $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, 70);
     print $doleditor->Create(1);
-    /*
-    print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">';
-    print $note_public;
-    print '</textarea></td></tr>';
-	*/
+   
 
     if (! $user->societe_id)
     {
         print '<tr><td>'.$langs->trans("NotePrivate").'</td><td valign="top">';
-        require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-        $doleditor=new DolEditor('note', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, 70);
+        $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, 70);
         print $doleditor->Create(1);
-        /*
-        print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">';
-        print $note_private;
-        print '</textarea>';*/
         print '</td></tr>';
     }
 
diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php
index f502d10d39b5e9c44c46fea6c2bfe42bfd352b7c..ee66e4583f7d5d9ba44d6dcbe6f7ee8cff96b462 100644
--- a/htdocs/contrat/note.php
+++ b/htdocs/contrat/note.php
@@ -50,13 +50,13 @@ $object->fetch($id,$ref);
 
 if ($action == 'setnote_public' && $user->rights->contrat->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(dol_htmlcleanlastbr(GETPOST('note_public')), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(dol_htmlcleanlastbr(GETPOST('note_public')), ENT_QUOTES),'_pubic');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->contrat->creer)
+else if ($action == 'setnote_private' && $user->rights->contrat->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(dol_htmlcleanlastbr(GETPOST('note')), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(dol_htmlcleanlastbr(GETPOST('note_private')), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/core/admin_extrafields.inc.php b/htdocs/core/admin_extrafields.inc.php
index 02eab4db893a3b0d64b494085c525f171cce5534..0b608a1e736024fc201edf131908d060c65022e8 100644
--- a/htdocs/core/admin_extrafields.inc.php
+++ b/htdocs/core/admin_extrafields.inc.php
@@ -66,6 +66,13 @@ if ($action == 'add')
         	$mesg[]=$langs->trans("ErrorNoValueForSelectType");
         	$action = 'create';
         }
+        if (GETPOST('type')=='sellist' && !GETPOST('param'))
+        {
+        	$error++;
+        	$langs->load("errors");
+        	$mesg[]=$langs->trans("ErrorNoValueForSelectListType");
+        	$action = 'create';
+        }
         if (GETPOST('type')=='checkbox' && !GETPOST('param'))
         {
         	$error++;
@@ -82,30 +89,30 @@ if ($action == 'add')
         }
         if  (((GETPOST('type')=='radio') || (GETPOST('type')=='checkbox') || (GETPOST('type')=='radio')) && GETPOST('param')) 
         {
-        		// Construct array for parameter (value of select list)
-    			$parameters = GETPOST('param');
-    			$parameters_array = explode("\r\n",$parameters);
-    			foreach($parameters_array as $param_ligne)
-    			{
-    				if (!empty($param_ligne)) {
-	    				if (preg_match_all('/,/',$param_ligne,$matches)) 
-	    				{
-	    					if (count($matches[0])>1) {
-	    						$error++;
-	    						$langs->load("errors");
-	    						$mesg[]=$langs->trans("ErrorBadFormatValueList",$param_ligne);
-	    						$action = 'create';
-	    					}
-	    				}
-	    				else 
-	    				{
+        	// Construct array for parameter (value of select list)
+    		$parameters = GETPOST('param');
+    		$parameters_array = explode("\r\n",$parameters);
+    		foreach($parameters_array as $param_ligne)
+    		{
+    			if (!empty($param_ligne)) {
+	    			if (preg_match_all('/,/',$param_ligne,$matches)) 
+	    			{
+	    				if (count($matches[0])>1) {
 	    					$error++;
 	    					$langs->load("errors");
 	    					$mesg[]=$langs->trans("ErrorBadFormatValueList",$param_ligne);
 	    					$action = 'create';
 	    				}
-    				}
-    			}  	
+	    			}
+	    			else 
+	    			{
+	    				$error++;
+	    				$langs->load("errors");
+	    				$mesg[]=$langs->trans("ErrorBadFormatValueList",$param_ligne);
+	    				$action = 'create';
+	    			}
+    			}
+    		}  	
         }
 
 	    if (! $error)
@@ -114,6 +121,7 @@ if ($action == 'add')
     		if (isset($_POST["attrname"]) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$_POST['attrname']))
     		{
     			// Construct array for parameter (value of select list)
+        		$default_value = GETPOST('default_value');
     			$parameters = GETPOST('param');
     			$parameters_array = explode("\r\n",$parameters);
     			foreach($parameters_array as $param_ligne)
@@ -186,6 +194,13 @@ if ($action == 'update')
         	$mesg[]=$langs->trans("ErrorNoValueForSelectType");
         	$action = 'edit';
         }
+        if (GETPOST('type')=='sellist' && !GETPOST('param'))
+        {
+        	$error++;
+        	$langs->load("errors");
+        	$mesg[]=$langs->trans("ErrorNoValueForSelectListType");
+        	$action = 'edit';
+        }
         if (GETPOST('type')=='checkbox' && !GETPOST('param'))
         {
         	$error++;
@@ -291,4 +306,4 @@ if ($action == 'delete')
 	}
 }
 
-?>
\ No newline at end of file
+?>
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index f7bc6938043168e4b5a92facc36fc30c3109e6e3..e1c4be9718468b96ae8f87b8f6f08cbbeb3d4819 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -1400,77 +1400,52 @@ abstract class CommonObject
     }
 
     /**
-     *  Update private note of element
+     *  Update note of element
      *
-     *  @param      string		$note	New value for note
-     *  @return     int      		   	<0 if KO, >0 if OK
+     *  @param      string		$note		New value for note
+     *  @param		string		$suffix		'', '_public' or '_private'
+     *  @return     int      		   		<0 if KO, >0 if OK
      */
-    function update_note($note)
+    function update_note($note,$suffix='')
     {
-        if (! $this->table_element)
-        {
-            dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
-            return -1;
-        }
+    	if (! $this->table_element)
+    	{
+    		dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
+    		return -1;
+    	}
 
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
-        // TODO uniformize fields to note_private
-        if ($this->table_element == 'fichinter' || $this->table_element == 'projet' || $this->table_element == 'projet_task')
-        {
-            $sql.= " SET note_private = '".$this->db->escape($note)."'";
-        }
-        else
-        {
-            $sql.= " SET note = '".$this->db->escape($note)."'";
-        }
-        $sql.= " WHERE rowid =". $this->id;
+    	$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+    	$sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
+    	$sql.= " WHERE rowid =". $this->id;
 
-        dol_syslog(get_class($this)."::update_note sql=".$sql, LOG_DEBUG);
-        if ($this->db->query($sql))
-        {
-            $this->note = $note;            // deprecated
-            $this->note_private = $note;
-            return 1;
-        }
-        else
-        {
-            $this->error=$this->db->error();
-            dol_syslog(get_class($this)."::update_note error=".$this->error, LOG_ERR);
-            return -1;
-        }
+    	dol_syslog(get_class($this)."::update_note sql=".$sql, LOG_DEBUG);
+    	if ($this->db->query($sql))
+    	{
+    		if ($suffix == '_public') $this->note_public = $note;
+    		else if ($suffix == '_private') $this->note_private = $note;
+    		else $this->note = $note;
+    		return 1;
+    	}
+    	else
+    	{
+    		$this->error=$this->db->lasterror();
+    		dol_syslog(get_class($this)."::update_note error=".$this->error, LOG_ERR);
+    		return -1;
+    	}
     }
 
     /**
-     * Update public note of element
-     *
-     * @param	string	$note_public	New value for note
-     * @return	int         			<0 if KO, >0 if OK
+     * 	Update public note (kept for backward compatibility)
+     * 
+     *  @param      string		$note		New value for note
+     *  @return     int      		   		<0 if KO, >0 if OK
+     *  @deprecated
      */
-    function update_note_public($note_public)
+    function update_note_public($note)
     {
-        if (! $this->table_element)
-        {
-            dol_syslog(get_class($this)."::update_note_public was called on objet with property table_element not defined",LOG_ERR);
-            return -1;
-        }
-
-        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
-        $sql.= " SET note_public = '".$this->db->escape($note_public)."'";
-        $sql.= " WHERE rowid =". $this->id;
-
-        dol_syslog(get_class($this)."::update_note_public sql=".$sql);
-        if ($this->db->query($sql))
-        {
-            $this->note_public = $note_public;
-            return 1;
-        }
-        else
-        {
-            $this->error=$this->db->error();
-            return -1;
-        }
+    	return $this->update_note($note,'_public');
     }
-
+    
     /**
      *	Update total_ht, total_ttc and total_vat for an object (sum of lines)
      *
diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php
index 764438a273c63cf8c008ef1c7d2dda075ee53e52..06510e28199542b5e352b5257489b427d10636b7 100644
--- a/htdocs/core/class/conf.class.php
+++ b/htdocs/core/class/conf.class.php
@@ -331,7 +331,8 @@ class Conf
 
 		// societe
 		if (empty($this->global->SOCIETE_CODECLIENT_ADDON))       $this->global->SOCIETE_CODECLIENT_ADDON="mod_codeclient_leopard";
-		if (empty($this->global->SOCIETE_CODEFOURNISSEUR_ADDON))  $this->global->SOCIETE_CODEFOURNISSEUR_ADDON=$this->global->SOCIETE_CODECLIENT_ADDON;
+		// Unused constant and for avoid problem with multicompany sharing
+		//if (empty($this->global->SOCIETE_CODEFOURNISSEUR_ADDON))  $this->global->SOCIETE_CODEFOURNISSEUR_ADDON=$this->global->SOCIETE_CODECLIENT_ADDON;
 		if (empty($this->global->SOCIETE_CODECOMPTA_ADDON))       $this->global->SOCIETE_CODECOMPTA_ADDON="mod_codecompta_panicum";
 
         // Security
diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php
index 978f0896f6578e909c7c53a6aada6c242daa1b27..0d4bbcf6d7a15d3faf9c4520ecf650e26f805710 100644
--- a/htdocs/core/lib/admin.lib.php
+++ b/htdocs/core/lib/admin.lib.php
@@ -252,18 +252,20 @@ function run_sql($sqlfile,$silent=1,$entity='',$usesavepoint=1,$handler='',$oker
             // Ajout trace sur requete (eventuellement a commenter si beaucoup de requetes)
             if (! $silent) print '<tr><td valign="top">'.$langs->trans("Request").' '.($i+1)." sql='".dol_htmlentities($newsql,ENT_NOQUOTES)."'</td></tr>\n";
             dol_syslog('Admin.lib::run_sql Request '.($i+1).' sql='.$newsql, LOG_DEBUG);
+			$sqlmodified=0;
 
             // Replace for encrypt data
-            if (preg_match_all('/__ENCRYPT\(\'([A-Za-z0-9_\"\[\]]+)\'\)__/i',$newsql,$reg))
+            if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i',$newsql,$reg))
             {
                 $num=count($reg[0]);
 
-                for($i=0;$i<$num;$i++)
+                for($j=0;$j<$num;$j++)
                 {
-                    $from 	= $reg[0][$i];
-                    $to		= $db->encrypt($reg[1][$i],1);
+                    $from 	= $reg[0][$j];
+                    $to		= $db->encrypt($reg[1][$j],1);
                     $newsql	= str_replace($from,$to,$newsql);
                 }
+                $sqlmodified++;
             }
 
             // Replace for decrypt data
@@ -271,12 +273,13 @@ function run_sql($sqlfile,$silent=1,$entity='',$usesavepoint=1,$handler='',$oker
             {
                 $num=count($reg[0]);
 
-                for($i=0;$i<$num;$i++)
+                for($j=0;$j<$num;$j++)
                 {
-                    $from 	= $reg[0][$i];
-                    $to		= $db->decrypt($reg[1][$i]);
+                    $from 	= $reg[0][$j];
+                    $to		= $db->decrypt($reg[1][$j]);
                     $newsql	= str_replace($from,$to,$newsql);
                 }
+                $sqlmodified++;
             }
 
             // Replace __x__ with rowid of insert nb x
@@ -294,9 +297,11 @@ function run_sql($sqlfile,$silent=1,$entity='',$usesavepoint=1,$handler='',$oker
                 $from='__'.$cursor.'__';
                 $to=$listofinsertedrowid[$cursor];
                 $newsql=str_replace($from,$to,$newsql);
-                dol_syslog('Admin.lib::run_sql New Request '.($i+1).' (replacing '.$from.' to '.$to.') sql='.$newsql, LOG_DEBUG);
+                $sqlmodified++;
             }
 
+            if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i+1).' sql='.$newsql, LOG_DEBUG);
+
             $result=$db->query($newsql,$usesavepoint);
             if ($result)
             {
diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php
index cb701a07c8d5d99a50df34e6c0aef4ccb494ad51..c591b2c023c586aae9af7db5d796d022b628356d 100644
--- a/htdocs/core/lib/company.lib.php
+++ b/htdocs/core/lib/company.lib.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2006		Rodolphe Quiedeville	<rodolphe@quiedeville.org>
  * Copyright (C) 2007		Patrick Raguin			<patrick.raguin@gmail.com>
  * Copyright (C) 2010-2012	Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -85,7 +86,7 @@ function societe_prepare_head($object)
     if ($user->societe_id == 0)
     {
     	// Notes
-        $head[$h][0] = DOL_URL_ROOT.'/societe/note.php?socid='.$object->id;
+        $head[$h][0] = DOL_URL_ROOT.'/societe/note.php?id='.$object->id;
         $head[$h][1] = $langs->trans("Note");
         $head[$h][2] = 'note';
         $h++;
@@ -529,7 +530,7 @@ function show_contacts($conf,$langs,$db,$object,$backtopage='')
     }
     print "</tr>";
 
-    $sql = "SELECT p.rowid, p.lastname, p.firstname, p.fk_pays, p.poste, p.phone, p.phone_mobile, p.fax, p.email, p.note ";
+    $sql = "SELECT p.rowid, p.lastname, p.firstname, p.fk_pays, p.poste, p.phone, p.phone_mobile, p.fax, p.email ";
     $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
     $sql .= " WHERE p.fk_soc = ".$object->id;
     $sql .= " ORDER by p.datec";
diff --git a/htdocs/core/lib/fourn.lib.php b/htdocs/core/lib/fourn.lib.php
index 4d3ebbb0b05ced8d3c87c8035b93429c4378b458..0ae8a67c60b7dc9cc56fd60ec59ddae5dd07cf1f 100644
--- a/htdocs/core/lib/fourn.lib.php
+++ b/htdocs/core/lib/fourn.lib.php
@@ -171,16 +171,19 @@ function supplierorder_admin_prepare_head($object)
 
 	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierorder_extrafields.php';
 	$head[$h][1] = $langs->trans("ExtraFieldsSupplierOrders");
-	$head[$h][2] = 'attributes';
+	$head[$h][2] = 'supplierorder';
 	$h++;
 
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'supplierorder_admin');
-
 	$head[$h][0] = DOL_URL_ROOT."/admin/supplier_invoice.php";
 	$head[$h][1] = $langs->trans("SuppliersInvoice");
 	$head[$h][2] = 'invoice';
 	$h++;
 
+	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoice_extrafields.php';
+	$head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoices");
+	$head[$h][2] = 'supplierinvoice';
+	$h++;
+
 	complete_head_from_modules($conf,$langs,$object,$head,$h,'supplierorder_admin','remove');
 
 	return $head;
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index 04c92c8be0d55bdec5dbc3e7984f01df03096bbe..38a65fc54accf2e5c6dbca37c5cd8a29b9cf0c21 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -3544,16 +3544,17 @@ function dol_textishtml($msg,$option=0)
 	{
 		if (preg_match('/<html/i',$msg))				return true;
 		elseif (preg_match('/<body/i',$msg))			return true;
+		elseif (preg_match('/<b>/i',$msg))				return true;
 		elseif (preg_match('/<br/i',$msg))				return true;
-		elseif (preg_match('/<span/i',$msg))			return true;
 		elseif (preg_match('/<div/i',$msg))				return true;
-		elseif (preg_match('/<li/i',$msg))				return true;
-		elseif (preg_match('/<table/i',$msg))			return true;
+		elseif (preg_match('/<em>/i',$msg))				return true;
 		elseif (preg_match('/<font/i',$msg))			return true;
-		elseif (preg_match('/<strong/i',$msg))			return true;
 		elseif (preg_match('/<img/i',$msg))				return true;
 		elseif (preg_match('/<i>/i',$msg))				return true;
-		elseif (preg_match('/<b>/i',$msg))				return true;
+		elseif (preg_match('/<li/i',$msg))				return true;
+		elseif (preg_match('/<span/i',$msg))			return true;
+		elseif (preg_match('/<strong/i',$msg))			return true;
+		elseif (preg_match('/<table/i',$msg))			return true;
 		elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg))	return true;    // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
 		elseif (preg_match('/&#[0-9]{2,3};/i',$msg))	return true;    // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
 		return false;
diff --git a/htdocs/core/lib/invoice2.lib.php b/htdocs/core/lib/invoice2.lib.php
index a73855accb49a5a91886d777b810e0f0941733ee..057dffd7d13925af3f1135ec459fa1ca5a2230af 100644
--- a/htdocs/core/lib/invoice2.lib.php
+++ b/htdocs/core/lib/invoice2.lib.php
@@ -1,7 +1,6 @@
-#!/usr/bin/php
 <?php
 /*
- * Copyright (C) 2009-2012 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2009-2013 Laurent Destailleur  <eldy@users.sourceforge.net>
 *
 * 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
@@ -29,22 +28,23 @@ require_once(DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php');
 
 /**
  * Function to build a compiled PDF
- * 
- * @param	DoliDB		$db						Database handler					
- * @param	Translate	$langs					Object langs					
- * @param	Conf		$conf					Object conf					
+ *
+ * @param	DoliDB		$db						Database handler
+ * @param	Translate	$langs					Object langs
+ * @param	Conf		$conf					Object conf
  * @param	string		$diroutputpdf			Dir to output file
  * @param	string		$newlangid				Lang id
  * @param 	array		$filter					Array with filters
- * @param 	date		$dateafterdate			Invoice after date 
+ * @param 	date		$dateafterdate			Invoice after date
  * @param 	date 		$datebeforedate			Invoice before date
  * @param 	date		$paymentdateafter		Payment after date
  * @param 	date		$paymentdatebefore		Payment before date
  * @param	int			$usestdout				Add information onto standard output
- * @param	int			$regenerate				''=Use existing PDF files, 'nameofpdf'=Regenerate all PDF files using the template, 
- * @return	int									Error code 
+ * @param	int			$regenerate				''=Use existing PDF files, 'nameofpdf'=Regenerate all PDF files using the template
+ * @param	string		$option					Suffix to add into file name of generated PDF
+ * @return	int									Error code
  */
-function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, $usestdout, $regenerate=0)
+function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, $usestdout, $regenerate=0, $option='')
 {
 	$sql = "SELECT DISTINCT f.rowid, f.facnumber";
 	$sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
@@ -104,19 +104,19 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 	}
 	if ($sqlwhere) $sql.=$sqlwhere;
 	if ($sqlorder) $sql.=$sqlorder;
-	
+
 	//print $sql; exit;
 	dol_syslog("scripts/invoices/rebuild_merge.php: sql=".$sql);
-	
+
 	if ($usestdout) print '--- start'."\n";
-	
+
 	// Start of transaction
 	//$db->begin();
-	
+
 	$error = 0;
 	$result = 0;
 	$files = array() ;		// liste les fichiers
-	
+
 	dol_syslog("scripts/invoices/rebuild_merge.php sql=".$sql);
 	if ( $resql=$db->query($sql) )
 	{
@@ -125,16 +125,16 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 	    $oldemail = '';
 	    $message = '';
 	    $total = '';
-	
+
 	    if ($num)
 	    {
 	    	// First loop on each resultset to build PDF
 	    	// -----------------------------------------
-	
+
 	        while ($cpt < $num)
 	        {
 	            $obj = $db->fetch_object($resql);
-	
+
 				$fac = new Facture($db);
 				$result=$fac->fetch($obj->rowid);
 				if ($result > 0)
@@ -157,35 +157,35 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 					else {
 					    if ($usestdout) print "PDF for invoice ".$obj->facnumber." already exists\n";
 					}
-	
+
 					// Add file into files array
 					$files[] = $filename;
 				}
-	
+
 				if ($result <= 0)
 				{
 					$error++;
-					if ($usestdout) print "Error: Failed to build PDF for invoice ".$fac->ref."\n";
-					else dol_syslog("Failed to build PDF for invoice ".$fac->ref, LOG_ERR);
+					if ($usestdout) print "Error: Failed to build PDF for invoice ".($fac->ref?$fac->ref:' id '.$obj->rowid)."\n";
+					else dol_syslog("Failed to build PDF for invoice ".($fac->ref?$fac->ref:' id '.$obj->rowid), LOG_ERR);
 				}
-	
+
 	            $cpt++;
 	        }
-	
 
-	        // Define format of output PDF 
+
+	        // Define format of output PDF
 	        $formatarray=pdf_getFormat();
 	        $page_largeur = $formatarray['width'];
 	        $page_hauteur = $formatarray['height'];
 	        $format = array($page_largeur,$page_hauteur);
-	        
+
 	        if ($usestdout) print "Using output PDF format ".join('x',$format)."\n";
 	        else dol_syslog("Using output PDF format ".join('x',$format), LOG_ERR);
-	        
-	        
+
+
 	        // Now, build a merged files with all files in $files array
 			//---------------------------------------------------------
-	        
+
 	        // Create empty PDF
 	        $pdf=pdf_getInstance($format);
 	        if (class_exists('TCPDF'))
@@ -193,12 +193,12 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 	            $pdf->setPrintHeader(false);
 	            $pdf->setPrintFooter(false);
 	        }
-	        $pdf->SetFont(pdf_getPDFFont($outputlangs));
-	
+	        $pdf->SetFont(pdf_getPDFFont($langs));
+
 	        if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false);
 			//$pdf->SetCompression(false);
-	
-	
+
+
 			//$pdf->Open();
 			//$pdf->AddPage();
 			//$title=$langs->trans("BillsCustomersUnpaid");
@@ -224,21 +224,26 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 
 			// Create output dir if not exists
 			dol_mkdir($diroutputpdf);
-	
+
 			// Save merged file
 			$filename='mergedpdf';
-	
+
 			if (! empty($option)) $filename.='_'.$option;
-	
-			if ($pagecount)
+			$file=$diroutputpdf.'/'.$filename.'.pdf';
+
+			if (! $error && $pagecount)
 			{
-				$file=$diroutputpdf.'/'.$filename.'.pdf';
 				$pdf->Output($file,'F');
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
 			}
-	
-			if ($usestdout) print "Merged PDF has been built in ".$file."\n";
+
+			if ($usestdout)
+			{
+				if (! $error) print "Merged PDF has been built in ".$file."\n";
+				else print "Can't build PDF ".$file."\n";
+			}
+
 			$result = 1;
 	    }
 	    else
@@ -254,7 +259,7 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte
 	    dol_syslog("scripts/invoices/rebuild_merge.php: Error");
 	    $error++;
 	}
-	
+
 	if ($error) return -1;
 	else return $result;
 }
diff --git a/htdocs/core/lib/sendings.lib.php b/htdocs/core/lib/sendings.lib.php
index 78fd0b9f0e03f6f78f3ea73697ba54e438ddf0b5..2d4728c07d4b3b7a1c978e5fdba0fd8d228a185a 100644
--- a/htdocs/core/lib/sendings.lib.php
+++ b/htdocs/core/lib/sendings.lib.php
@@ -63,6 +63,11 @@ function shipping_prepare_head($object)
 	$head[$h][1] = $langs->trans("ContactsAddresses");
 	$head[$h][2] = 'contact';
 	$h++;
+	
+	$head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$object->id;
+	$head[$h][1] = $langs->trans("Notes");
+	$head[$h][2] = 'note';
+	$h++;
 
 	// Show more tabs from modules
 	// Entries must be declared in modules descriptor with line
diff --git a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
index 5ab40fd1e867fa6740bc1d795c395d5a2666bedc..00658b7b9cb2d9d3f2866760c4917ea91065b082 100644
--- a/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
+++ b/htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
@@ -1,21 +1,21 @@
 <?php
 /* Copyright (C) 2010-2012 	Laurent Destailleur <eldy@users.sourceforge.net>
  * Copyright (C) 2012		Juanjo Menent		<jmenent@2byte.es>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * or see http://www.gnu.org/
- */
+*
+* 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
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+* or see http://www.gnu.org/
+*/
 
 /**
  *	\file       htdocs/core/modules/commande/doc/doc_generic_order_odt.modules.php
@@ -86,84 +86,84 @@ class doc_generic_order_odt extends ModelePDFCommandes
 	}
 
 
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Object			$object             Main object to use as data source
-     * @param   Translate		$outputlangs        Lang object to use for output
-     * @return	array								Array of substitution
-     */
-    function get_substitutionarray_object($object,$outputlangs)
-    {
-        global $conf;
-
-        $resarray=array(
-            'object_id'=>$object->id,
-            'object_ref'=>$object->ref,
-            'object_ref_ext'=>$object->ref_ext,
-        	'object_ref_customer'=>$object->ref_client,
-        	'object_date'=>dol_print_date($object->date,'day'),
-        	'object_date_delivery'=>dol_print_date($object->date_livraison,'dayhour'),
-        	'object_date_creation'=>dol_print_date($object->date_creation,'day'),
-        	'object_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
-        	'object_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
-        	'object_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
-        	'object_date_close'=>dol_print_date($object->date_cloture,'dayhour'),
-            'object_payment_mode_code'=>$object->mode_reglement_code,
-           	'object_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
-           	'object_payment_term_code'=>$object->cond_reglement_code,
-           	'object_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):$object->cond_reglement),
-        	'object_total_ht'=>price($object->total_ht,0,$outputlangs),
-            'object_total_vat'=>price($object->total_tva,0,$outputlangs),
-            'object_total_ttc'=>price($object->total_ttc,0,$outputlangs),
-            'object_total_discount_ht' => price($object->getTotalDiscount(), 0, $outputlangs),
-            'object_vatrate'=>vatrate($object->tva),
-            'object_note_private'=>$object->note,
-            'object_note'=>$object->note_public,
-        );
-
-        // Add vat by rates
-        foreach ($object->lines as $line)
-        {
-        	if (empty($resarray['object_total_vat_'.$line->tva_tx])) $resarray['object_total_vat_'.$line->tva_tx]=0;
-        	$resarray['object_total_vat_'.$line->tva_tx]+=$line->total_tva;
-        }
-
-        return $resarray;
-    }
-
-    /**
-     *	Define array with couple substitution key => substitution value
-     *
-     *	@param  array			$line				Array of lines
-     *	@param  Translate		$outputlangs        Lang object to use for output
-     *  @return	array								Return a substitution array
-     */
-    function get_substitutionarray_lines($line,$outputlangs)
-    {
-        global $conf;
-
-        return array(
-            'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
-            'line_product_ref'=>$line->product_ref,
-            'line_product_label'=>$line->product_label,
-        	'line_desc'=>$line->desc,
-            'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
-            'line_up'=>price($line->subprice, 0, $outputlangs),
-            'line_qty'=>$line->qty,
-            'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
-            'line_price_ht'=>price($line->total_ht, 0, $outputlangs),
-            'line_price_ttc'=>price($line->total_ttc, 0, $outputlangs),
-            'line_price_vat'=>price($line->total_tva, 0, $outputlangs),
-            'line_date_start'=>$line->date_start,
-            'line_date_end'=>$line->date_end
-        );
-    }
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Object			$object             Main object to use as data source
+	 * @param   Translate		$outputlangs        Lang object to use for output
+	 * @return	array								Array of substitution
+	 */
+	function get_substitutionarray_object($object,$outputlangs)
+	{
+		global $conf;
+
+		$resarray=array(
+		'object_id'=>$object->id,
+		'object_ref'=>$object->ref,
+		'object_ref_ext'=>$object->ref_ext,
+		'object_ref_customer'=>$object->ref_client,
+		'object_date'=>dol_print_date($object->date,'day'),
+		'object_date_delivery'=>dol_print_date($object->date_livraison,'dayhour'),
+		'object_date_creation'=>dol_print_date($object->date_creation,'day'),
+		'object_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
+		'object_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
+		'object_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
+		'object_date_close'=>dol_print_date($object->date_cloture,'dayhour'),
+		'object_payment_mode_code'=>$object->mode_reglement_code,
+		'object_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
+		'object_payment_term_code'=>$object->cond_reglement_code,
+		'object_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):$object->cond_reglement),
+		'object_total_ht'=>price($object->total_ht,0,$outputlangs),
+		'object_total_vat'=>price($object->total_tva,0,$outputlangs),
+		'object_total_ttc'=>price($object->total_ttc,0,$outputlangs),
+		'object_total_discount_ht' => price($object->getTotalDiscount(), 0, $outputlangs),
+		'object_vatrate'=>vatrate($object->tva),
+		'object_note_private'=>$object->note,
+		'object_note'=>$object->note_public,
+		);
+
+		// Add vat by rates
+		foreach ($object->lines as $line)
+		{
+			if (empty($resarray['object_total_vat_'.$line->tva_tx])) $resarray['object_total_vat_'.$line->tva_tx]=0;
+			$resarray['object_total_vat_'.$line->tva_tx]+=$line->total_tva;
+		}
+
+		return $resarray;
+	}
+
+	/**
+	 *	Define array with couple substitution key => substitution value
+	 *
+	 *	@param  array			$line				Array of lines
+	 *	@param  Translate		$outputlangs        Lang object to use for output
+	 *  @return	array								Return a substitution array
+	 */
+	function get_substitutionarray_lines($line,$outputlangs)
+	{
+		global $conf;
+
+		return array(
+		'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
+		'line_product_ref'=>$line->product_ref,
+		'line_product_label'=>$line->product_label,
+		'line_desc'=>$line->desc,
+		'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
+		'line_up'=>price($line->subprice, 0, $outputlangs),
+		'line_qty'=>$line->qty,
+		'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
+		'line_price_ht'=>price($line->total_ht, 0, $outputlangs),
+		'line_price_ttc'=>price($line->total_ttc, 0, $outputlangs),
+		'line_price_vat'=>price($line->total_tva, 0, $outputlangs),
+		'line_date_start'=>$line->date_start,
+		'line_date_end'=>$line->date_end
+		);
+	}
 
 	/**
 	 *	Return description of a module
 	 *
-     *	@param	Translate	$langs      Lang object to use for output
+	 *	@param	Translate	$langs      Lang object to use for output
 	 *	@return string       			Description
 	 */
 	function info($langs)
@@ -191,7 +191,9 @@ class doc_generic_order_odt extends ModelePDFCommandes
 		{
 			$tmpdir=trim($tmpdir);
 			$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
-			if (! $tmpdir) { unset($listofdir[$key]); continue; }
+			if (! $tmpdir) {
+				unset($listofdir[$key]); continue;
+			}
 			if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
 			else
 			{
@@ -202,19 +204,19 @@ class doc_generic_order_odt extends ModelePDFCommandes
 		$texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
 		// Add list of substitution keys
 		$texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
- 		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
+		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
 
 		$texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
 		$texte.= '<table><tr><td>';
 		$texte.= '<textarea class="flat" cols="60" name="value1">';
 		$texte.=$conf->global->COMMANDE_ADDON_PDF_ODT_PATH;
 		$texte.= '</textarea>';
-        $texte.= '</td>';
+		$texte.= '</td>';
 		$texte.= '<td align="center">&nbsp; ';
-        $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
-        $texte.= '</td>';
+		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
+		$texte.= '</td>';
 		$texte.= '</tr>';
-        $texte.= '</table>';
+		$texte.= '</table>';
 
 		// Scan directories
 		if (count($listofdir)) $texte.=$langs->trans("NumberOfModelFilesFound").': <b>'.count($listoffiles).'</b>';
@@ -228,7 +230,7 @@ class doc_generic_order_odt extends ModelePDFCommandes
 		$texte.= '</tr>';
 
 		/*$texte.= '<tr>';
-		$texte.= '<td align="center">';
+		 $texte.= '<td align="center">';
 		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
 		$texte.= '</td>';
 		$texte.= '</tr>';*/
@@ -245,9 +247,9 @@ class doc_generic_order_odt extends ModelePDFCommandes
 	 *	@param		Commande	$object				Object source to build document
 	 *	@param		Translate	$outputlangs		Lang output object
 	 * 	@param		string		$srctemplatepath	Full path of source filename for generator using a template file
-     *  @param		int			$hidedetails		Do not show line details
-     *  @param		int			$hidedesc			Do not show desc
-     *  @param		int			$hideref			Do not show ref
+	 *  @param		int			$hidedetails		Do not show line details
+	 *  @param		int			$hidedesc			Do not show desc
+	 *  @param		int			$hideref			Do not show ref
 	 *	@return		int         					1 if OK, <=0 if KO
 	 */
 	function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
@@ -260,14 +262,14 @@ class doc_generic_order_odt extends ModelePDFCommandes
 			return -1;
 		}
 
-                // Add odtgeneration hook
-                if (! is_object($hookmanager))
-                {
-                        include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-                        $hookmanager=new HookManager($this->db);
-                }
-                $hookmanager->initHooks(array('odtgeneration'));
-                global $action;
+		// Add odtgeneration hook
+		if (! is_object($hookmanager))
+		{
+			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			$hookmanager=new HookManager($this->db);
+		}
+		$hookmanager->initHooks(array('odtgeneration'));
+		global $action;
 
 		if (! is_object($outputlangs)) $outputlangs=$langs;
 		$sav_charset_output=$outputlangs->charset_output;
@@ -314,7 +316,7 @@ class doc_generic_order_odt extends ModelePDFCommandes
 				$newfiletmp=preg_replace('/\.odt/i','',$newfile);
 				$newfiletmp=preg_replace('/template_/i','',$newfiletmp);
 				$newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
-			    $newfiletmp=$objectref.'_'.$newfiletmp;
+				$newfiletmp=$objectref.'_'.$newfiletmp;
 				//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
 				$file=$dir.'/'.$newfiletmp.'.odt';
 				//print "newdir=".$dir;
@@ -325,64 +327,64 @@ class doc_generic_order_odt extends ModelePDFCommandes
 				dol_mkdir($conf->commande->dir_temp);
 
 
-                // If BILLING contact defined on invoice, we use it
-                $usecontact=false;
-                $arrayidcontact=$object->getIdContact('external','BILLING');
-                if (count($arrayidcontact) > 0)
-                {
-                    $usecontact=true;
-                    $result=$object->fetch_contact($arrayidcontact[0]);
-                }
-
-                // Recipient name
-                if (! empty($usecontact))
-                {
-                    // On peut utiliser le nom de la societe du contact
-                    if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
-                    else $socobject = $object->client;
-                }
-                else
-                {
-                    $socobject=$object->client;
-                }
-
-                // Make substitution
-                $substitutionarray=array(
-                    '__FROM_NAME__' => $this->emetteur->nom,
-                    '__FROM_EMAIL__' => $this->emetteur->email,
-                    '__TOTAL_TTC__' => $object->total_ttc,
-                    '__TOTAL_HT__' => $object->total_ht,
-                    '__TOTAL_VAT__' => $object->total_vat
-                );
-                complete_substitutions_array($substitutionarray, $langs, $object);
-                // Call the ODTSubstitution hook
-                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
-                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+				// If BILLING contact defined on invoice, we use it
+				$usecontact=false;
+				$arrayidcontact=$object->getIdContact('external','BILLING');
+				if (count($arrayidcontact) > 0)
+				{
+					$usecontact=true;
+					$result=$object->fetch_contact($arrayidcontact[0]);
+				}
+
+				// Recipient name
+				if (! empty($usecontact))
+				{
+					// On peut utiliser le nom de la societe du contact
+					if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
+					else $socobject = $object->client;
+				}
+				else
+				{
+					$socobject=$object->client;
+				}
+
+				// Make substitution
+				$substitutionarray=array(
+				'__FROM_NAME__' => $this->emetteur->nom,
+				'__FROM_EMAIL__' => $this->emetteur->email,
+				'__TOTAL_TTC__' => $object->total_ttc,
+				'__TOTAL_HT__' => $object->total_ht,
+				'__TOTAL_VAT__' => $object->total_vat
+				);
+				complete_substitutions_array($substitutionarray, $langs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Line of free text
 				$newfreetext='';
 				$paramfreetext='COMMANDE_FREE_TEXT';
-			    if (! empty($conf->global->$paramfreetext))
-			    {
-			        $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
-			    }
+				if (! empty($conf->global->$paramfreetext))
+				{
+					$newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
+				}
 
-                // Open and load template
+				// Open and load template
 				require_once ODTPHP_PATH.'odf.php';
 				$odfHandler = new odf(
-				    $srctemplatepath,
-				    array(
-						'PATH_TO_TMP'	  => $conf->commande->dir_temp,
-						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
-						'DELIMITER_LEFT'  => '{',
-						'DELIMITER_RIGHT' => '}'
+					$srctemplatepath,
+					array(
+					'PATH_TO_TMP'	  => $conf->commande->dir_temp,
+					'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
+					'DELIMITER_LEFT'  => '{',
+					'DELIMITER_RIGHT' => '}'
 					)
 				);
 				// After construction $odfHandler->contentXml contains content and
 				// [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
 				// [!-- BEGIN lines --]*[!-- END lines --]
-                //print html_entity_decode($odfHandler->__toString());
-                //print exit;
+				//print html_entity_decode($odfHandler->__toString());
+				//print exit;
 
 
 				// Make substitutions into odt of freetext
@@ -393,29 +395,29 @@ class doc_generic_order_odt extends ModelePDFCommandes
 				{
 				}
 
-                // Make substitutions into odt of user info
+				// Make substitutions into odt of user info
 				$tmparray=$this->get_substitutionarray_user($user,$outputlangs);
-                //var_dump($tmparray); exit;
-                foreach($tmparray as $key=>$value)
-                {
-                    try {
-                        if (preg_match('/logo$/',$key)) // Image
-                        {
-                            //var_dump($value);exit;
-                            if (file_exists($value)) $odfHandler->setImage($key, $value);
-                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
-                        }
-                        else    // Text
-                        {
-                            $odfHandler->setVars($key, $value, true, 'UTF-8');
-                        }
-                    }
-                    catch(OdfException $e)
-                    {
-                    }
-                }
-                // Make substitutions into odt of mysoc
-                $tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
+				//var_dump($tmparray); exit;
+				foreach($tmparray as $key=>$value)
+				{
+					try {
+						if (preg_match('/logo$/',$key)) // Image
+						{
+							//var_dump($value);exit;
+							if (file_exists($value)) $odfHandler->setImage($key, $value);
+							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
+						}
+						else    // Text
+						{
+							$odfHandler->setVars($key, $value, true, 'UTF-8');
+						}
+					}
+					catch(OdfException $e)
+					{
+					}
+				}
+				// Make substitutions into odt of mysoc
+				$tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
 				//var_dump($tmparray); exit;
 				foreach($tmparray as $key=>$value)
 				{
@@ -435,7 +437,7 @@ class doc_generic_order_odt extends ModelePDFCommandes
 					{
 					}
 				}
-                // Make substitutions into odt of thirdparty
+				// Make substitutions into odt of thirdparty
 				$tmparray=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
 				foreach($tmparray as $key=>$value)
 				{
@@ -455,73 +457,73 @@ class doc_generic_order_odt extends ModelePDFCommandes
 					}
 				}
 				// Replace tags of object + external modules
-			    $tmparray=$this->get_substitutionarray_object($object,$outputlangs);
-			    complete_substitutions_array($tmparray, $outputlangs, $object);
-                                // Call the ODTSubstitution hook
-                                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-                                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-                foreach($tmparray as $key=>$value)
-                {
-                    try {
-                        if (preg_match('/logo$/',$key)) // Image
-                        {
-                            if (file_exists($value)) $odfHandler->setImage($key, $value);
-                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
-                        }
-                        else    // Text
-                        {
-                            $odfHandler->setVars($key, $value, true, 'UTF-8');
-                        }
-                    }
-                    catch(OdfException $e)
-                    {
-                    }
-                }
+				$tmparray=$this->get_substitutionarray_object($object,$outputlangs);
+				complete_substitutions_array($tmparray, $outputlangs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+				foreach($tmparray as $key=>$value)
+				{
+					try {
+						if (preg_match('/logo$/',$key)) // Image
+						{
+							if (file_exists($value)) $odfHandler->setImage($key, $value);
+							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
+						}
+						else    // Text
+						{
+							$odfHandler->setVars($key, $value, true, 'UTF-8');
+						}
+					}
+					catch(OdfException $e)
+					{
+					}
+				}
 				// Replace tags of lines
-                try
-                {
-                    $listlines = $odfHandler->setSegment('lines');
-                    foreach ($object->lines as $line)
-                    {
-                        $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
-                        complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
-                        // Call the ODTSubstitutionLine hook
-                        $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
-                        $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-                        foreach($tmparray as $key => $val)
-                        {
-                             try
-                             {
-                                $listlines->setVars($key, $val, true, 'UTF-8');
-                             }
-                             catch(OdfException $e)
-                             {
-                             }
-                             catch(SegmentException $e)
-                             {
-                             }
-                        }
-                        $listlines->merge();
-                    }
-                    $odfHandler->mergeSegment($listlines);
-                }
-                catch(OdfException $e)
-                {
-                    $this->error=$e->getMessage();
-                    dol_syslog($this->error, LOG_WARNING);
-                    return -1;
-                }
-
-                                // Call the beforeODTSave hook
+				try
+				{
+					$listlines = $odfHandler->setSegment('lines');
+					foreach ($object->lines as $line)
+					{
+						$tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
+						complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
+						// Call the ODTSubstitutionLine hook
+						$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
+						$reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+						foreach($tmparray as $key => $val)
+						{
+							try
+							{
+								$listlines->setVars($key, $val, true, 'UTF-8');
+							}
+							catch(OdfException $e)
+							{
+							}
+							catch(SegmentException $e)
+							{
+							}
+						}
+						$listlines->merge();
+					}
+					$odfHandler->mergeSegment($listlines);
+				}
+				catch(OdfException $e)
+				{
+					$this->error=$e->getMessage();
+					dol_syslog($this->error, LOG_WARNING);
+					return -1;
+				}
+
+				// Call the beforeODTSave hook
 				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
-                // Write new file
+				// Write new file
 				//$result=$odfHandler->exportAsAttachedFile('toto');
 				$odfHandler->saveToDisk($file);
 
 				if (! empty($conf->global->MAIN_UMASK))
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
+					@chmod($file, octdec($conf->global->MAIN_UMASK));
 
 				$odfHandler=null;	// Destroy object
 
diff --git a/htdocs/core/modules/expedition/doc/pdf_expedition_merou.modules.php b/htdocs/core/modules/expedition/doc/pdf_expedition_merou.modules.php
index 39c70faab796d06c490a4353e5dfaa822b702520..4f6f04cc7422dd356a69cb80073d464d69e234c4 100644
--- a/htdocs/core/modules/expedition/doc/pdf_expedition_merou.modules.php
+++ b/htdocs/core/modules/expedition/doc/pdf_expedition_merou.modules.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2005      Rodolphe Quiedeville <rodolphe@quiedeville.org>
  * Copyright (C) 2005-2012 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2011 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -191,6 +192,27 @@ class pdf_expedition_merou extends ModelePdfExpedition
 				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
 				$tab_height = $this->page_hauteur - $tab_top - $heightforfooter;
 				$tab_height_newpage = $this->page_hauteur - $tab_top_newpage - $heightforfooter;
+				
+				// Affiche notes
+				if (! empty($object->note_public))
+				{				
+					$pdf->SetFont('','', $default_font_size - 1);
+					$pdf->writeHTMLCell(190, 3, $this->marge_gauche, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
+					$nexY = $pdf->GetY();
+					$height_note=$nexY-$tab_top;
+				
+					// Rect prend une longueur en 3eme param
+					$pdf->SetDrawColor(192,192,192);
+					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
+				
+					$tab_height = $tab_height - $height_note;
+					$tab_top = $nexY+6;
+				}
+				else
+				{
+					$height_note=0;
+				}
+				
 
 				$pdf->SetFillColor(240,240,240);
 				$pdf->SetTextColor(0,0,0);
diff --git a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
index 77f673f222077c9805ea91066c1b070fee1159fb..512bf98be8b4bbd4b006e665e9b8c2e3a1d1bdc4 100644
--- a/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
+++ b/htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
@@ -2,20 +2,20 @@
 /* Copyright (C) 2010-2012	Laurent Destailleur	<ely@users.sourceforge.net>
  * Copyright (C) 2012		Regis Houssin		<regis.houssin@capnetworks.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
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * or see http://www.gnu.org/
- */
+* 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
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+* or see http://www.gnu.org/
+*/
 
 /**
  *	\file       htdocs/core/modules/facture/doc/doc_generic_invoice_odt.modules.php
@@ -86,55 +86,55 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 	}
 
 
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Object			$object             Main object to use as data source
-     * @param   Translate		$outputlangs        Lang object to use for output
-     * @return	array								Array of substitution
-     */
-    function get_substitutionarray_object($object,$outputlangs)
-    {
-        global $conf;
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Object			$object             Main object to use as data source
+	 * @param   Translate		$outputlangs        Lang object to use for output
+	 * @return	array								Array of substitution
+	 */
+	function get_substitutionarray_object($object,$outputlangs)
+	{
+		global $conf;
 
-        $invoice_source=new Facture($this->db);
+		$invoice_source=new Facture($this->db);
 		if ($object->fk_facture_source > 0)
 		{
-        	$invoice_source->fetch($object->fk_facture_source);
+			$invoice_source->fetch($object->fk_facture_source);
 		}
 		$sumpayed = $object->getSommePaiement();
 		$alreadypayed=price($sumpayed,0,$outputlangs);
 
-        $resarray=array(
-            'object_id'=>$object->id,
-            'object_ref'=>$object->ref,
-            'object_ref_ext'=>$object->ref_ext,
-        	'object_ref_customer'=>$object->ref_client,
-            'object_ref_supplier'=>(! empty($object->ref_fournisseur)?$object->ref_fournisseur:''),
-            'object_source_invoice_ref'=>$invoice_source->ref,
-        	'object_date'=>dol_print_date($object->date,'day'),
-        	'object_date_limit'=>dol_print_date($object->date_lim_reglement,'day'),
-        	'object_date_creation'=>dol_print_date($object->date_creation,'day'),
-            'object_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
-            'object_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
-        	'object_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
-            'object_payment_mode_code'=>$object->mode_reglement_code,
-        	'object_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
-        	'object_payment_term_code'=>$object->cond_reglement_code,
-        	'object_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):$object->cond_reglement),
-        	'object_total_ht'=>price2num($object->total_ht),
-            'object_total_vat'=>price2num($object->total_tva),
-            'object_total_ttc'=>price2num($object->total_ttc),
-            'object_total_discount_ht' => price2num($object->getTotalDiscount(), 0, $outputlangs),
-            'object_vatrate'=>(isset($object->tva)?vatrate($object->tva):''),
-            'object_note_private'=>$object->note,
-            'object_note'=>$object->note_public,
-        	// Payments
-            'object_already_payed'=>$alreadypayed,
-            'object_remain_to_pay'=>price2num($object->total_ttc - $sumpayed)
-        );
-
-        // Add vat by rates
+		$resarray=array(
+		'object_id'=>$object->id,
+		'object_ref'=>$object->ref,
+		'object_ref_ext'=>$object->ref_ext,
+		'object_ref_customer'=>$object->ref_client,
+		'object_ref_supplier'=>(! empty($object->ref_fournisseur)?$object->ref_fournisseur:''),
+		'object_source_invoice_ref'=>$invoice_source->ref,
+		'object_date'=>dol_print_date($object->date,'day'),
+		'object_date_limit'=>dol_print_date($object->date_lim_reglement,'day'),
+		'object_date_creation'=>dol_print_date($object->date_creation,'day'),
+		'object_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
+		'object_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
+		'object_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
+		'object_payment_mode_code'=>$object->mode_reglement_code,
+		'object_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
+		'object_payment_term_code'=>$object->cond_reglement_code,
+		'object_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):$object->cond_reglement),
+		'object_total_ht'=>price2num($object->total_ht),
+		'object_total_vat'=>price2num($object->total_tva),
+		'object_total_ttc'=>price2num($object->total_ttc),
+		'object_total_discount_ht' => price2num($object->getTotalDiscount(), 0, $outputlangs),
+		'object_vatrate'=>(isset($object->tva)?vatrate($object->tva):''),
+		'object_note_private'=>$object->note,
+		'object_note'=>$object->note_public,
+		// Payments
+		'object_already_payed'=>$alreadypayed,
+		'object_remain_to_pay'=>price2num($object->total_ttc - $sumpayed)
+		);
+
+		// Add vat by rates
 		foreach ($object->lines as $line)
 		{
 			if (empty($resarray['object_total_vat_'.$line->tva_tx])) $resarray['object_total_vat_'.$line->tva_tx]=0;
@@ -152,41 +152,41 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 
 			$resarray = $this->fill_substitutionarray_with_extrafields($object,$resarray,$extrafields,$array_key='object',$outputlangs);
 		}
-        return $resarray;
-    }
-
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   array		$line			Array of lines
-     * @param   Translate	$outputlangs    Lang object to use for output
-     * @return	array						Return substitution array
-     */
-    function get_substitutionarray_lines($line,$outputlangs)
-    {
-        global $conf;
-
-        return array(
-            'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
-            'line_product_ref'=>$line->product_ref,
-            'line_product_label'=>$line->product_label,
-        	'line_desc'=>$line->desc,
-            'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
-            'line_up'=>price($line->subprice, 0, $outputlangs),
-            'line_qty'=>$line->qty,
-            'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
-            'line_price_ht'=>price2num($line->total_ht),
-            'line_price_ttc'=>price2num($line->total_ttc),
-            'line_price_vat'=>price2num($line->total_tva),
-            'line_date_start'=>dol_print_date($line->date_start, 'day', false, $outputlangs),
-            'line_date_end'=>dol_print_date($line->date_end, 'day', false, $outputlangs),
-        );
-    }
+		return $resarray;
+	}
+
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   array		$line			Array of lines
+	 * @param   Translate	$outputlangs    Lang object to use for output
+	 * @return	array						Return substitution array
+	 */
+	function get_substitutionarray_lines($line,$outputlangs)
+	{
+		global $conf;
+
+		return array(
+		'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
+		'line_product_ref'=>$line->product_ref,
+		'line_product_label'=>$line->product_label,
+		'line_desc'=>$line->desc,
+		'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
+		'line_up'=>price($line->subprice, 0, $outputlangs),
+		'line_qty'=>$line->qty,
+		'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
+		'line_price_ht'=>price2num($line->total_ht),
+		'line_price_ttc'=>price2num($line->total_ttc),
+		'line_price_vat'=>price2num($line->total_tva),
+		'line_date_start'=>dol_print_date($line->date_start, 'day', false, $outputlangs),
+		'line_date_end'=>dol_print_date($line->date_end, 'day', false, $outputlangs),
+		);
+	}
 
 	/**
 	 * Return description of a module
 	 *
-     * @param	Translate	$langs      Lang object to use for output
+	 * @param	Translate	$langs      Lang object to use for output
 	 * @return	string      			Description
 	 */
 	function info($langs)
@@ -214,7 +214,9 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 		{
 			$tmpdir=trim($tmpdir);
 			$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
-			if (! $tmpdir) { unset($listofdir[$key]); continue; }
+			if (! $tmpdir) {
+				unset($listofdir[$key]); continue;
+			}
 			if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
 			else
 			{
@@ -225,19 +227,19 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 		$texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
 		// Add list of substitution keys
 		$texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
- 		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
+		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
 
 		$texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
 		$texte.= '<table><tr><td>';
 		$texte.= '<textarea class="flat" cols="60" name="value1">';
 		$texte.=$conf->global->FACTURE_ADDON_PDF_ODT_PATH;
 		$texte.= '</textarea>';
-        $texte.= '</td>';
+		$texte.= '</td>';
 		$texte.= '<td align="center">&nbsp; ';
-        $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
-        $texte.= '</td>';
+		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
+		$texte.= '</td>';
 		$texte.= '</tr>';
-        $texte.= '</table>';
+		$texte.= '</table>';
 
 		// Scan directories
 		if (count($listofdir)) $texte.=$langs->trans("NumberOfModelFilesFound").': <b>'.count($listoffiles).'</b>';
@@ -251,7 +253,7 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 		$texte.= '</tr>';
 
 		/*$texte.= '<tr>';
-		$texte.= '<td align="center">';
+		 $texte.= '<td align="center">';
 		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
 		$texte.= '</td>';
 		$texte.= '</tr>';*/
@@ -268,9 +270,9 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 	 *	@param		Facture		$object				Object source to build document
 	 *	@param		Translate	$outputlangs		Lang output object
 	 * 	@param		string		$srctemplatepath	Full path of source filename for generator using a template file
-     *  @param		int			$hidedetails		Do not show line details
-     *  @param		int			$hidedesc			Do not show desc
-     *  @param		int			$hideref			Do not show ref
+	 *  @param		int			$hidedetails		Do not show line details
+	 *  @param		int			$hidedesc			Do not show desc
+	 *  @param		int			$hideref			Do not show ref
 	 *	@return		int         					1 if OK, <=0 if KO
 	 */
 	function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
@@ -283,14 +285,14 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 			return -1;
 		}
 
-                // Add odtgeneration hook
-                if (! is_object($hookmanager))
-                {
-                        include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-                        $hookmanager=new HookManager($this->db);
-                }
-                $hookmanager->initHooks(array('odtgeneration'));
-                global $action;
+		// Add odtgeneration hook
+		if (! is_object($hookmanager))
+		{
+			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			$hookmanager=new HookManager($this->db);
+		}
+		$hookmanager->initHooks(array('odtgeneration'));
+		global $action;
 
 		if (! is_object($outputlangs)) $outputlangs=$langs;
 		$sav_charset_output=$outputlangs->charset_output;
@@ -337,7 +339,7 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 				$newfiletmp=preg_replace('/\.odt/i','',$newfile);
 				$newfiletmp=preg_replace('/template_/i','',$newfiletmp);
 				$newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
-			    $newfiletmp=$objectref.'_'.$newfiletmp;
+				$newfiletmp=$objectref.'_'.$newfiletmp;
 				//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
 				$file=$dir.'/'.$newfiletmp.'.odt';
 				//print "newdir=".$dir;
@@ -348,70 +350,70 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 				dol_mkdir($conf->facture->dir_temp);
 
 
-                // If BILLING contact defined on invoice, we use it
-                $usecontact=false;
-                $arrayidcontact=$object->getIdContact('external','BILLING');
-                if (count($arrayidcontact) > 0)
-                {
-                    $usecontact=true;
-                    $result=$object->fetch_contact($arrayidcontact[0]);
-                }
-
-                // Recipient name
-                if (! empty($usecontact))
-                {
-                    // On peut utiliser le nom de la societe du contact
-                    if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
-                    else $socobject = $object->client;
-                }
-                else
-                {
-                    $socobject=$object->client;
-                }
-
-                // Fetch info for linked propal
-                $linked_propal = $object->fetchObjectLinked('','','','');
-                //print_r($object->linkedObjects['propal']); exit;
-
-                $propal_object = $object->linkedObjects['propal'][0];
-
-                // Make substitution
-                $substitutionarray=array(
-                    '__FROM_NAME__' => $this->emetteur->nom,
-                    '__FROM_EMAIL__' => $this->emetteur->email,
-                    '__TOTAL_TTC__' => $object->total_ttc,
-                    '__TOTAL_HT__' => $object->total_ht,
-                    '__TOTAL_VAT__' => $object->total_tva
-                );
-                complete_substitutions_array($substitutionarray, $langs, $object);
-                // Call the ODTSubstitution hook
-                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
-                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+				// If BILLING contact defined on invoice, we use it
+				$usecontact=false;
+				$arrayidcontact=$object->getIdContact('external','BILLING');
+				if (count($arrayidcontact) > 0)
+				{
+					$usecontact=true;
+					$result=$object->fetch_contact($arrayidcontact[0]);
+				}
+
+				// Recipient name
+				if (! empty($usecontact))
+				{
+					// On peut utiliser le nom de la societe du contact
+					if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
+					else $socobject = $object->client;
+				}
+				else
+				{
+					$socobject=$object->client;
+				}
+
+				// Fetch info for linked propal
+				$linked_propal = $object->fetchObjectLinked('','','','');
+				//print_r($object->linkedObjects['propal']); exit;
+
+				$propal_object = $object->linkedObjects['propal'][0];
+
+				// Make substitution
+				$substitutionarray=array(
+				'__FROM_NAME__' => $this->emetteur->nom,
+				'__FROM_EMAIL__' => $this->emetteur->email,
+				'__TOTAL_TTC__' => $object->total_ttc,
+				'__TOTAL_HT__' => $object->total_ht,
+				'__TOTAL_VAT__' => $object->total_tva
+				);
+				complete_substitutions_array($substitutionarray, $langs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Line of free text
 				$newfreetext='';
 				$paramfreetext='FACTURE_FREE_TEXT';
-			    if (! empty($conf->global->$paramfreetext))
-			    {
-			        $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
-			    }
+				if (! empty($conf->global->$paramfreetext))
+				{
+					$newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
+				}
 
-                // Open and load template
+				// Open and load template
 				require_once ODTPHP_PATH.'odf.php';
 				$odfHandler = new odf(
-				    $srctemplatepath,
-				    array(
-						'PATH_TO_TMP'	  => $conf->facture->dir_temp,
-						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
-						'DELIMITER_LEFT'  => '{',
-						'DELIMITER_RIGHT' => '}'
+					$srctemplatepath,
+					array(
+					'PATH_TO_TMP'	  => $conf->facture->dir_temp,
+					'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
+					'DELIMITER_LEFT'  => '{',
+					'DELIMITER_RIGHT' => '}'
 					)
 				);
 				// After construction $odfHandler->contentXml contains content and
 				// [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
 				// [!-- BEGIN lines --]*[!-- END lines --]
-                //print html_entity_decode($odfHandler->__toString());
-                //print exit;
+				//print html_entity_decode($odfHandler->__toString());
+				//print exit;
 
 
 				// Make substitutions into odt of freetext
@@ -422,7 +424,7 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 				{
 				}
 
-                // Make substitutions into odt of user info
+				// Make substitutions into odt of user info
 				$array_user=$this->get_substitutionarray_user($user,$outputlangs);
 				$array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
 				$array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
@@ -432,74 +434,74 @@ class doc_generic_invoice_odt extends ModelePDFFactures
 
 				$tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_objet,$array_propal);
 				complete_substitutions_array($tmparray, $outputlangs, $object);
-                                // Call the ODTSubstitution hook
-                                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-                                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-
-                //var_dump($tmparray); exit;
-                foreach($tmparray as $key=>$value)
-                {
-                    try {
-                        if (preg_match('/logo$/',$key)) // Image
-                        {
-                            //var_dump($value);exit;
-                            if (file_exists($value)) $odfHandler->setImage($key, $value);
-                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
-                        }
-                        else    // Text
-                        {
-                            $odfHandler->setVars($key, $value, true, 'UTF-8');
-                        }
-                    }
-                    catch(OdfException $e)
-                    {
-                    }
-                }
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+
+				//var_dump($tmparray); exit;
+				foreach($tmparray as $key=>$value)
+				{
+					try {
+						if (preg_match('/logo$/',$key)) // Image
+						{
+							//var_dump($value);exit;
+							if (file_exists($value)) $odfHandler->setImage($key, $value);
+							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
+						}
+						else    // Text
+						{
+							$odfHandler->setVars($key, $value, true, 'UTF-8');
+						}
+					}
+					catch(OdfException $e)
+					{
+					}
+				}
 				// Replace tags of lines
-                try
-                {
-                    $listlines = $odfHandler->setSegment('lines');
-                    foreach ($object->lines as $line)
-                    {
-                        $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
-                        complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
-                        // Call the ODTSubstitutionLine hook
-                        $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
-                        $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-                        foreach($tmparray as $key => $val)
-                        {
-                             try
-                             {
-                                $listlines->setVars($key, $val, true, 'UTF-8');
-                             }
-                             catch(OdfException $e)
-                             {
-                             }
-                             catch(SegmentException $e)
-                             {
-                             }
-                        }
-                        $listlines->merge();
-                    }
-                    $odfHandler->mergeSegment($listlines);
-                }
-                catch(OdfException $e)
-                {
-                    $this->error=$e->getMessage();
-                    dol_syslog($this->error, LOG_WARNING);
-                    return -1;
-                }
-
-                                // Call the beforeODTSave hook
+				try
+				{
+					$listlines = $odfHandler->setSegment('lines');
+					foreach ($object->lines as $line)
+					{
+						$tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
+						complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
+						// Call the ODTSubstitutionLine hook
+						$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
+						$reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+						foreach($tmparray as $key => $val)
+						{
+							try
+							{
+								$listlines->setVars($key, $val, true, 'UTF-8');
+							}
+							catch(OdfException $e)
+							{
+							}
+							catch(SegmentException $e)
+							{
+							}
+						}
+						$listlines->merge();
+					}
+					$odfHandler->mergeSegment($listlines);
+				}
+				catch(OdfException $e)
+				{
+					$this->error=$e->getMessage();
+					dol_syslog($this->error, LOG_WARNING);
+					return -1;
+				}
+
+				// Call the beforeODTSave hook
 				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
-                // Write new file
+				// Write new file
 				//$result=$odfHandler->exportAsAttachedFile('toto');
 				$odfHandler->saveToDisk($file);
 
 				if (! empty($conf->global->MAIN_UMASK))
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
+					@chmod($file, octdec($conf->global->MAIN_UMASK));
 
 				$odfHandler=null;	// Destroy object
 
diff --git a/htdocs/core/modules/mailings/contacts1.modules.php b/htdocs/core/modules/mailings/contacts1.modules.php
index 3c44c5e15ce91416bed4611f02c95f8b2f81a3a9..f45969ea564db2cc9410892953887ad3241b6418 100755
--- a/htdocs/core/modules/mailings/contacts1.modules.php
+++ b/htdocs/core/modules/mailings/contacts1.modules.php
@@ -71,11 +71,8 @@ class mailing_contacts1 extends MailingTargets
 		$statssql=array();
 		$statssql[0] = "SELECT '".$langs->trans("NbOfCompaniesContacts")."' as label,";
 		$statssql[0].= " count(distinct(c.email)) as nb";
-		$statssql[0].= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
-		$statssql[0].= " ".MAIN_DB_PREFIX."societe as s";
-		$statssql[0].= " WHERE s.rowid = c.fk_soc";
-		$statssql[0].= " AND c.entity IN (".getEntity('societe', 1).")";
-		$statssql[0].= " AND s.client IN (1, 3)";
+		$statssql[0].= " FROM ".MAIN_DB_PREFIX."socpeople as c";
+		$statssql[0].= " WHERE c.entity IN (".getEntity('societe', 1).")";
 		$statssql[0].= " AND c.email != ''";      // Note that null != '' is false
 		$statssql[0].= " AND c.no_email = 0";
 
@@ -96,12 +93,11 @@ class mailing_contacts1 extends MailingTargets
 		global $conf;
 
 		$sql  = "SELECT count(distinct(c.email)) as nb";
-		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
-		$sql .= " ".MAIN_DB_PREFIX."societe as s";
-		$sql .= " WHERE s.rowid = c.fk_soc";
-		$sql .= " AND c.entity IN (".getEntity('societe', 1).")";
-		$sql .= " AND c.email != ''"; // Note that null != '' is false
-		$sql .= " AND c.no_email = 0";
+		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = c.fk_soc";
+		$sql.= " WHERE c.entity IN (".getEntity('societe', 1).")";
+		$sql.= " AND c.email != ''"; // Note that null != '' is false
+		$sql.= " AND c.no_email = 0";
 
 		// La requete doit retourner un champ "nb" pour etre comprise
 		// par parent::getNbOfRecipients
@@ -203,10 +199,9 @@ class mailing_contacts1 extends MailingTargets
 		$sql = "SELECT c.rowid as id, c.email as email, c.rowid as fk_contact,";
 		$sql.= " c.lastname, c.firstname, c.civilite,";
 		$sql.= " s.nom as companyname";
-		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
-		$sql.= " ".MAIN_DB_PREFIX."societe as s";
-		$sql.= " WHERE s.rowid = c.fk_soc";
-		$sql.= " AND c.entity IN (".getEntity('societe', 1).")";
+		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = c.fk_soc";
+		$sql.= " WHERE c.entity IN (".getEntity('societe', 1).")";
 		$sql.= " AND c.email != ''";
 		$sql.= " AND c.no_email = 0";
 		foreach($filtersarray as $key)
diff --git a/htdocs/core/modules/mailings/contacts2.modules.php b/htdocs/core/modules/mailings/contacts2.modules.php
index 955a126912b17238ee0838ac7e7fa57fee5fb082..5a25a11e59064313141f10955c7214af8d376494 100755
--- a/htdocs/core/modules/mailings/contacts2.modules.php
+++ b/htdocs/core/modules/mailings/contacts2.modules.php
@@ -1,5 +1,6 @@
 <?php
-/* Copyright (C) 2011 François Cerbelle <francois@cerbelle.net>
+/* Copyright (C) 2011	François Cerbelle	<francois@cerbelle.net>
+ * Copyright (C) 2013	Regis Houssin		<regis.houssin@capnetworks.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
@@ -80,14 +81,13 @@ class mailing_contacts2 extends MailingTargets
         $sql = "SELECT sp.rowid as id, sp.email as email, sp.rowid as fk_contact,";
         $sql.= " sp.lastname, sp.firstname as firstname, sp.civilite,";
         $sql.= " s.nom as companyname";
-    	$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-        $sql.= " WHERE s.rowid = sp.fk_soc";
+    	$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = sp.fk_soc";
+        $sql.= " WHERE sp.entity IN (".getEntity('societe', 1).")";
     	$sql.= " AND sp.email != ''";  // Note that null != '' is false
     	$sql.= " AND sp.no_email = 0";
     	//$sql.= " AND sp.poste != ''";
-    	$sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
-    	if ($filtersarray[0]<>'all') $sql.= " AND sp.poste ='".$filtersarray[0]."'";
+    	if ($filtersarray[0]<>'all') $sql.= " AND sp.poste ='".$this->db->escape($filtersarray[0])."'";
     	$sql.= " ORDER BY sp.lastname, sp.firstname";
     	$resql = $this->db->query($sql);
     	if ($resql)
@@ -162,10 +162,9 @@ class mailing_contacts2 extends MailingTargets
         // Number with a filter are show in the combo list for each filter.
         // If we want a filter "a position is defined", we must add it into formFilter
     	$sql = "SELECT count(distinct(sp.email)) as nb";
-    	$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-        $sql.= " WHERE s.rowid = sp.fk_soc";
-        $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
+    	$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = sp.fk_soc";
+        $sql.= " WHERE sp.entity IN (".getEntity('societe', 1).")";
     	$sql.= " AND sp.email != ''";  // Note that null != '' is false
     	$sql.= " AND sp.no_email = 0";
     	//$sql.= " AND sp.poste != ''";
@@ -187,10 +186,8 @@ class mailing_contacts2 extends MailingTargets
     	$langs->load("companies");
 
         $sql = "SELECT sp.poste, count(distinct(sp.email)) AS nb";
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-        $sql.= " WHERE s.rowid = sp.fk_soc";
-        $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
+        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
+        $sql.= " WHERE sp.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND sp.email != ''";    // Note that null != '' is false
         $sql.= " AND sp.no_email = 0";
         $sql.= " AND (sp.poste IS NOT NULL AND sp.poste != '')";
diff --git a/htdocs/core/modules/mailings/contacts3.modules.php b/htdocs/core/modules/mailings/contacts3.modules.php
index b1955aa981e56b99de35a5b5f33c804ea7296071..600a855c975ac6c6aea6c792fc26ece4b7eb8179 100755
--- a/htdocs/core/modules/mailings/contacts3.modules.php
+++ b/htdocs/core/modules/mailings/contacts3.modules.php
@@ -79,12 +79,11 @@ class mailing_contacts3 extends MailingTargets
         $sql = "SELECT sp.rowid as id, sp.email as email, sp.rowid as fk_contact,";
         $sql.= " sp.lastname, sp.firstname, sp.civilite,";
         $sql.= " s.nom as companyname";
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-    	if ($filtersarray[0] <> 'all') $sql.= ", ".MAIN_DB_PREFIX."categorie as c,";
-    	if ($filtersarray[0] <> 'all') $sql.= " ".MAIN_DB_PREFIX."categorie_societe as cs";
-        $sql.= " WHERE s.rowid = sp.fk_soc";
-    	$sql.= " AND sp.email != ''";     // Note that null != '' is false
+        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
+    	if ($filtersarray[0] <> 'all') $sql.= ", ".MAIN_DB_PREFIX."categorie as c";
+    	if ($filtersarray[0] <> 'all') $sql.= ", ".MAIN_DB_PREFIX."categorie_societe as cs";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = sp.fk_soc";
+    	$sql.= " WHERE sp.email != ''";     // Note that null != '' is false
     	$sql.= " AND sp.no_email = 0";
     	$sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
     	if ($filtersarray[0] <> 'all') $sql.= " AND cs.fk_categorie = c.rowid";
@@ -168,10 +167,9 @@ class mailing_contacts3 extends MailingTargets
     	// Number with a filter are show in the combo list for each filter.
         // If we want a filter "is inside at least one category", we must add it into formFilter
     	$sql = "SELECT count(distinct(c.email)) as nb";
-        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-        $sql.= " WHERE s.rowid = c.fk_soc";
-        $sql.= " AND c.entity IN (".getEntity('societe', 1).")";
+        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c";
+    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = c.fk_soc";
+        $sql.= " WHERE c.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND c.email != ''"; // Note that null != '' is false
         $sql.= " AND c.no_email = 0";
         /*
@@ -205,11 +203,9 @@ class mailing_contacts3 extends MailingTargets
 
         $sql = "SELECT c.label, count(distinct(sp.email)) AS nb";
         $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s,";
         $sql.= " ".MAIN_DB_PREFIX."categorie as c,";
         $sql.= " ".MAIN_DB_PREFIX."categorie_societe as cs";
-        $sql.= " WHERE s.rowid = sp.fk_soc";
-        $sql.= " AND sp.email != ''";     // Note that null != '' is false
+        $sql.= " WHERE sp.email != ''";     // Note that null != '' is false
         $sql.= " AND sp.no_email = 0";
         $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND cs.fk_categorie = c.rowid";
diff --git a/htdocs/core/modules/mailings/pomme.modules.php b/htdocs/core/modules/mailings/pomme.modules.php
index 6e645b3581cf2c7c5413beacde4f4a8b4d749fd2..30c7c63da609f2c87a0bb73eb539971fe9412d7c 100644
--- a/htdocs/core/modules/mailings/pomme.modules.php
+++ b/htdocs/core/modules/mailings/pomme.modules.php
@@ -82,7 +82,7 @@ class mailing_pomme extends MailingTargets
      *	For example if this selector is used to extract 500 different
      *	emails from a text file, this function must return 500.
      *
-     *	@param	string	$sql		Requete sql de comptage
+     *	@param	string	$sql		SQL request to use to count
      *	@return	int					Number of recipients
      */
 	function getNbOfRecipients($sql='')
diff --git a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
index 4b621b705a2fe35d6f095846bb47539644732171..450773a25662ab98d45ce2de3a1ade2a7044f7fb 100755
--- a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
+++ b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php
@@ -175,11 +175,10 @@ class mailing_thirdparties_services_expired extends MailingTargets
      *	For example if this selector is used to extract 500 different
      *	emails from a text file, this function must return 500.
      *
-     *	@param	int		$filter		Filter
-     *	@param	string	$option		Option
+     *	@param	string	$sql		SQL request to use to count
      *	@return	int					Number of recipients
      */
-    function getNbOfRecipients($sql,$filter=1,$option='')
+    function getNbOfRecipients($sql='')
     {
         $now=dol_now();
 
diff --git a/htdocs/core/modules/modOpenSurvey.class.php b/htdocs/core/modules/modOpenSurvey.class.php
new file mode 100755
index 0000000000000000000000000000000000000000..e9385442a85735a1d0c221ddfdbb30e560f5295b
--- /dev/null
+++ b/htdocs/core/modules/modOpenSurvey.class.php
@@ -0,0 +1,224 @@
+<?php
+/* Copyright (C) 2008 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * Licensed under the GNU GPL v3 or higher (See file gpl-3.0.html)
+ */
+
+/**
+ * 		\defgroup   opensurvey     Module OpenSurvey
+ *      \brief      Module to OpenSurvey integration.
+ */
+
+/**
+ *      \file       htdocs/opensurvey/core/modules/modOpenSurvey.class.php
+ *      \ingroup    opensurvey
+ *      \brief      Description and activation file for module OpenSurvey
+ */
+include_once(DOL_DOCUMENT_ROOT ."/core/modules/DolibarrModules.class.php");
+
+
+/**
+ * Description and activation class for module opensurvey
+ */
+class modOpenSurvey extends DolibarrModules
+{
+
+	/**
+	 *   Constructor. Define names, constants, directories, boxes, permissions
+	 *
+	 *   @param		DoliDB		$db		Database handler
+	 */
+	function __construct($db)
+	{
+		global $langs,$conf;
+
+		$this->db = $db;
+
+		// Id for module (must be unique).
+		// Use here a free id (See in Home -> System information -> Dolibarr for list of used module id).
+		$this->numero = 55000;
+		// Key text used to identify module (for permission, menus, etc...)
+		$this->rights_class = 'opensurvey';
+
+		// Family can be 'crm','financial','hr','projects','product','technic','other'
+		// It is used to group modules in module setup page
+		$this->family = "projects";
+		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
+		$this->name = preg_replace('/^mod/i','',get_class($this));
+		// Module description used if translation string 'ModuleXXXDesc' not found (XXX is value MyModule)
+		$this->description = "Module to integrate a survey (like Doodle, Studs, Rdvz, ...)";
+		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
+		$this->version = 'dolibarr';
+		// Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase)
+		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
+		// Where to store the module in setup page (0=common,1=interface,2=others,3=very specific)
+		$this->special = 0;
+		// Name of image file used for this module.
+		// If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
+		// If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
+		$this->picto='opensurvey.png@opensurvey';
+
+		// Data directories to create when module is enabled
+		$this->dirs = array();
+		//$this->dirs[0] = DOL_DATA_ROOT.'/mymodule;
+		//$this->dirs[1] = DOL_DATA_ROOT.'/mymodule/temp;
+
+		// Config pages. Put here list of php page names stored in admin directory used to setup module
+		$this->config_page_url = array("index.php@opensurvey");
+
+		// Dependencies
+		$this->depends = array();		// List of modules id that must be enabled if this module is enabled
+		$this->requiredby = array();	// List of modules id to disable if this one is disabled
+		$this->phpmin = array(4,1);					// Minimum version of PHP required by module
+		$this->need_dolibarr_version = array(2,4);	// Minimum version of Dolibarr required by module
+
+		// Constants
+		$this->const = array();			// List of parameters
+
+		// Dictionnaries
+        $this->dictionnaries=array();
+
+		// Boxes
+		$this->boxes = array();			// List of boxes
+		$r=0;
+
+		// Add here list of php file(s) stored in includes/boxes that contains class to show a box.
+		// Example:
+		//$this->boxes[$r][1] = "myboxa.php";
+		//$r++;
+		//$this->boxes[$r][1] = "myboxb.php";
+		//$r++;
+
+		// Permissions
+		$this->rights = array();		// Permission array used by this module
+		$r=0;
+
+		// Add here list of permission defined by an id, a label, a boolean and two constant strings.
+		// Example:
+		$this->rights[$r][0] = 55000; 				// Permission id (must not be already used)
+		$this->rights[$r][1] = 'Read surveys';	// Permission label
+		$this->rights[$r][2] = 'r'; 					// Permission by default for new user (0/1)
+		$this->rights[$r][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[$r][4] = 'survey';				// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[$r][5] = 'read';				// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$r++;
+
+		// Add here list of permission defined by an id, a label, a boolean and two constant strings.
+		// Example:
+		$this->rights[$r][0] = 55001; 				// Permission id (must not be already used)
+		$this->rights[$r][1] = 'Create/modify surveys';	// Permission label
+		$this->rights[$r][2] = 'w'; 					// Permission by default for new user (0/1)
+		$this->rights[$r][3] = 0; 					// Permission by default for new user (0/1)
+		$this->rights[$r][4] = 'survey';				// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$this->rights[$r][5] = 'write';				// In php code, permission will be checked by test if ($user->rights->permkey->level1->level2)
+		$r++;
+
+
+		// Main menu entries
+		$this->menus = array();			// List of menus to add
+		$r=0;
+
+		$this->menu[$r]=array(	'fk_menu'=>0,		    						// Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
+								'type'=>'top',
+								'titre'=>'Surveys',
+								'mainmenu'=>'opensurvey',
+								'url'=>'/opensurvey/index.php',
+								'langs'=>'opensurvey@opensurvey',
+								'position'=>200,
+                				'enabled'=>'$conf->opensurvey->enabled',         // Define condition to show or hide menu entry. Use '$conf->NewsSubmitter->enabled' if entry must be visible if module is enabled.
+								'perms'=>'$user->rights->opensurvey->survey->read',
+								'target'=>'',
+								'user'=>0);
+		$r++;
+
+		$this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=opensurvey',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
+								'type'=>'left',
+								'titre'=>'Survey',
+								'mainmenu'=>'opensurvey',
+								'leftmenu'=>'opensurvey',
+								'url'=>'/opensurvey/index.php?mainmenu=opensurvey&leftmenu=opensurvey',
+								'langs'=>'opensurvey@opensurvey',
+								'position'=>200,
+                				'enabled'=>'$conf->opensurvey->enabled',         // Define condition to show or hide menu entry. Use '$conf->NewsSubmitter->enabled' if entry must be visible if module is enabled.
+								'perms'=>'',
+								'target'=>'',
+								'user'=>0);
+		$r++;
+
+		$this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=opensurvey,fk_leftmenu=opensurvey',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
+								'type'=>'left',
+								'titre'=>'NewSurvey',
+								'mainmenu'=>'opensurvey',
+								'leftmenu'=>'opensurvey_new',
+								'url'=>'/opensurvey/public/index.php?origin=dolibarr',
+								'langs'=>'opensurvey@opensurvey',
+								'position'=>210,
+                				'enabled'=>'$conf->opensurvey->enabled',         // Define condition to show or hide menu entry. Use '$conf->NewsSubmitter->enabled' if entry must be visible if module is enabled.
+								'perms'=>'',
+								'target'=>'_blank',
+								'user'=>0);
+		$r++;
+
+		$this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=opensurvey,fk_leftmenu=opensurvey',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
+								'type'=>'left',
+								'titre'=>'List',
+								'mainmenu'=>'opensurvey',
+								'leftmenu'=>'opensurvey_list',
+								'url'=>'/opensurvey/list.php',
+								'langs'=>'opensurvey@opensurvey',
+								'position'=>220,
+                				'enabled'=>'$conf->opensurvey->enabled',         // Define condition to show or hide menu entry. Use '$conf->NewsSubmitter->enabled' if entry must be visible if module is enabled.
+								'perms'=>'',
+								'target'=>'',
+								'user'=>0);
+		$r++;
+	}
+
+	/**
+	 *	Function called when module is enabled.
+	 *	The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
+	 *	It also creates data directories
+	 *
+     *  @param      string	$options    Options when enabling module ('', 'noboxes')
+	 *  @return     int             	1 if OK, 0 if KO
+	 */
+	function init($options='')
+	{
+		$sql = array();
+
+		$result=$this->load_tables();
+
+		return $this->_init($sql,$options);
+	}
+
+	/**
+	 *	Function called when module is disabled.
+	 *  Remove from database constants, boxes and permissions from Dolibarr database.
+	 *	Data directories are not deleted
+	 *
+     *  @param      string	$options    Options when enabling module ('', 'noboxes')
+	 *  @return     int             	1 if OK, 0 if KO
+	 */
+	function remove($options='')
+	{
+		$sql = array();
+
+		return $this->_remove($sql,$options);
+	}
+
+
+	/**
+	 *	Create tables and keys required by module
+	 * 	Files mymodule.sql and mymodule.key.sql with create table and create keys
+	 * 	commands must be stored in directory /mymodule/sql/
+	 *	This function is called by this->init.
+	 *
+	 * 	@return		int		<=0 if KO, >0 if OK
+	 */
+	function load_tables()
+	{
+	    return $this->_load_tables('/opensurvey/sql/');
+	}
+}
+
+?>
diff --git a/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php b/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
index 34cd23a0a7f93c2d42dbd7d93123e20518968134..4a230e8ca756f9ff057055ce9f2defe111cf3f30 100644
--- a/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
+++ b/htdocs/core/modules/project/pdf/doc_generic_project_odt.modules.php
@@ -125,7 +125,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 		'object_note_private'=>$object->note_private,
 		'object_note_public'=>$object->note_public,
 		'object_public'=>$object->public,
-		'object_statut'=>html_entity_decode($object->getLibStatut())
+		'object_statut'=>$object->getLibStatut()
 		);
 	}
 
@@ -209,7 +209,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 	function get_substitutionarray_project_reference($refdetail,$outputlangs)
 	{
 		global $conf;
-		
+
 		return array(
 		'projref_type'=>$refdetail['type'],
 		'projref_ref'=>$refdetail['ref'],
@@ -220,7 +220,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 		'projref_status'=>$refdetail['status']
 		);
 	}
-	
+
 	/**
 	 *	Define array with couple substitution key => substitution value
 	 *
@@ -242,7 +242,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 		'taskressource_email'=>$taskressource['email']
 		);
 	}
-	
+
 	/**
 	 *	Define array with couple substitution key => substitution value
 	 *
@@ -254,7 +254,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 	{
 		global $conf;
 
-		return array(		
+		return array(
 		'tasktime_rowid'=>$tasktime['rowid'],
 		'tasktime_task_date'=>dol_print_date($tasktime['task_date'],'day'),
 		'tasktime_task_duration'=>convertSecondToTime($tasktime['task_duration'],'all'),
@@ -265,7 +265,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 		'tasktime_fullcivname'=>$tasktime['fullcivname']
 		);
 	}
-	
+
 	/**
 	 *	Define array with couple substitution key => substitution value
 	 *
@@ -276,7 +276,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 	function get_substitutionarray_task_file($file,$outputlangs)
 	{
 		global $conf;
-	
+
 		return array(
 		'tasksfile_name'=>$file['name'],
 		'tasksfile_date'=>dol_print_date($file['date'],'day'),
@@ -384,6 +384,14 @@ class doc_generic_project_odt extends ModelePDFProjects
 			return -1;
 		}
 
+		// Add odtgeneration hook
+		if (! is_object($hookmanager))
+		{
+			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			$hookmanager=new HookManager($this->db);
+		}
+		$hookmanager->initHooks(array('odtgeneration'));
+		global $action;
 		if (! is_object($outputlangs)) $outputlangs=$langs;
 		$sav_charset_output=$outputlangs->charset_output;
 		$outputlangs->charset_output='UTF-8';
@@ -470,7 +478,6 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 				// Make substitutions into odt of user info
 				$tmparray=$this->get_substitutionarray_user($user,$outputlangs);
-				//var_dump($tmparray); exit;
 				foreach($tmparray as $key=>$value)
 				{
 					try {
@@ -504,6 +511,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 						else	// Text
 						{
 							$odfHandler->setVars($key, $value, true, 'UTF-8');
+							$odfHandler->setVarsHeadFooter($key, $value, true, 'UTF-8');
 						}
 					}
 					catch(OdfException $e)
@@ -534,6 +542,9 @@ class doc_generic_project_odt extends ModelePDFProjects
 				// Replace tags of object + external modules
 				$tmparray=$this->get_substitutionarray_object($object,$outputlangs);
 				complete_substitutions_array($tmparray, $outputlangs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 				foreach($tmparray as $key=>$value)
 				{
 					try {
@@ -564,7 +575,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 					if (!empty($object->fk_soc)) $socid = $object->fk_soc;
 
 					$tasksarray=$taskstatic->getTasksArray(0, 0, $object->id, $socid, 0);
-					
+						
 
 
 					foreach ($tasksarray as $task)
@@ -584,10 +595,10 @@ class doc_generic_project_odt extends ModelePDFProjects
 							{
 							}
 						}
-						
+
 						$taskobj=new Task($this->db);
 						$taskobj->fetch($task->id);
-						
+
 						// Replace tags of lines for contacts task
 						$sourcearray=array('internal','external');
 						$contact_arrray=array();
@@ -601,7 +612,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 						if ((is_array($contact_arrray) && count($contact_arrray) > 0))
 						{
 							$listlinestaskres = $listlines->__get('tasksressources');
-						
+
 							foreach ($contact_arrray as $contact)
 							{
 								if ($contact['source']=='internal') {
@@ -611,15 +622,15 @@ class doc_generic_project_odt extends ModelePDFProjects
 								} elseif ($contact['source']=='external') {
 									$objectdetail=new Contact($this->db);
 									$objectdetail->fetch($contact['id']);
-						
+
 									$soc=new Societe($this->db);
 									$soc->fetch($contact['socid']);
 									$contact['socname']=$soc->name;
 								}
 								$contact['fullname']=$objectdetail->getFullName($outputlangs,1);
-						
+
 								$tmparray=$this->get_substitutionarray_tasksressource($contact,$outputlangs);
-								
+
 								foreach($tmparray as $key => $val)
 								{
 									try
@@ -645,7 +656,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 						$sql .= " WHERE t.fk_task =".$task->id;
 						$sql .= " AND t.fk_user = u.rowid";
 						$sql .= " ORDER BY t.task_date DESC";
-						
+
 						$resql = $this->db->query($sql);
 						if ($resql)
 						{
@@ -663,9 +674,9 @@ class doc_generic_project_odt extends ModelePDFProjects
 								} else {
 									$row['fullcivname']='';
 								}
-								
+
 								$tmparray=$this->get_substitutionarray_taskstime($row,$outputlangs);
-								
+
 								foreach($tmparray as $key => $val)
 								{
 									try
@@ -684,15 +695,15 @@ class doc_generic_project_odt extends ModelePDFProjects
 							}
 							$this->db->free($resql);
 						}
-						
-						
+
+
 						// Replace tags of project files
 						$listtasksfiles = $listlines->__get('tasksfiles');
-						
+
 						$upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref).'/'.dol_sanitizeFileName($task->ref);
 						$filearray=dol_dir_list($upload_dir,"files",0,'','\.meta$','name',SORT_ASC,1);
-						
-						
+
+
 						foreach ($filearray as $filedetail)
 						{
 							$tmparray=$this->get_substitutionarray_task_file($filedetail,$outputlangs);
@@ -731,7 +742,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 					$upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref);
 					$filearray=dol_dir_list($upload_dir,"files",0,'','\.meta$','name',SORT_ASC,1);
 
-						
+
 					foreach ($filearray as $filedetail)
 					{
 						//dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true));
@@ -794,7 +805,6 @@ class doc_generic_project_odt extends ModelePDFProjects
 							$contact['fullname']=$objectdetail->getFullName($outputlangs,1);
 
 							$tmparray=$this->get_substitutionarray_project_contacts($contact,$outputlangs);
-							complete_substitutions_array($tmparray, $outputlangs, $contact, $contact, "completesubstitutionarray_lines");
 							foreach($tmparray as $key => $val)
 							{
 								try
@@ -891,27 +901,27 @@ class doc_generic_project_odt extends ModelePDFProjects
 								{
 									$ref_array=array();
 									$ref_array['type']=$langs->trans($classname);
-									
+										
 									$element = new $classname($this->db);
 									$element->fetch($elementarray[$i]);
 									$element->fetch_thirdparty();
-										
+
 									//Ref object
 									$ref_array['ref']=$element->ref;
-									
+										
 									//Date object
 									$dateref=$element->date;
 									if (empty($dateref)) $dateref=$element->datep;
 									if (empty($dateref)) $dateref=$element->date_contrat;
 									$ref_array['date']=$dateref;
-										
+
 									//Soc object
 									if (is_object($element->thirdparty)) {
 										$ref_array['socname']=$element->thirdparty->name;
 									} else {
 										$ref_array['socname']='';
 									}
-										
+
 									//Amount object
 									if (empty($valueref['disableamount'])) {
 										if (!empty($element->total_ht)) {
@@ -925,9 +935,9 @@ class doc_generic_project_odt extends ModelePDFProjects
 										$ref_array['amountht']='';
 										$ref_array['amountttc']='';
 									}
-										
-									$ref_array['status']=html_entity_decode($element->getLibStatut(0));
-										
+
+									$ref_array['status']=$element->getLibStatut(0);
+
 									$tmparray=$this->get_substitutionarray_project_reference($ref_array,$outputlangs);
 
 									foreach($tmparray as $key => $val)
@@ -945,7 +955,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 									}
 									$listlines->merge();
 								}
-								
+
 							}
 						}
 						$odfHandler->mergeSegment($listlines);
@@ -958,8 +968,14 @@ class doc_generic_project_odt extends ModelePDFProjects
 					return -1;
 				}
 
+				// Call the beforeODTSave hook
+				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
+				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+
+
 				// Write new file
-				$odfHandler->saveToDisk($file);
+				$odfHandler->saveToDisk($file);	
+				//$odfHandler->exportAsAttachedPDF($file);
 
 				if (! empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
diff --git a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
index df61cbed4611e1b1f699e7bde462fc303139a932..26d67f09a321f1b338c4ab7fc0f5cebe7e28b44e 100644
--- a/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
+++ b/htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
@@ -1,21 +1,21 @@
 <?php
 /* Copyright (C) 2010-2012 	Laurent Destailleur <eldy@users.sourceforge.net>
  * Copyright (C) 2012		Juanjo Menent		<jmenent@2byte.es>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * or see http://www.gnu.org/
- */
+*
+* 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
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+* or see http://www.gnu.org/
+*/
 
 /**
  *	\file       htdocs/core/modules/propale/doc/doc_generic_proposal_odt.modules.php
@@ -89,7 +89,7 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 	/**
 	 *	Return description of a module
 	 *
-     *	@param	Translate	$langs      Lang object to use for output
+	 *	@param	Translate	$langs      Lang object to use for output
 	 *	@return string       			Description
 	 */
 	function info($langs)
@@ -123,7 +123,9 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 		{
 			$tmpdir=trim($tmpdir);
 			$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
-			if (! $tmpdir) { unset($listofdir[$key]); continue; }
+			if (! $tmpdir) {
+				unset($listofdir[$key]); continue;
+			}
 			if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
 			else
 			{
@@ -134,19 +136,19 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 		$texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
 		// Add list of substitution keys
 		$texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
- 		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
+		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
 
 		$texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
 		$texte.= '<table><tr><td>';
 		$texte.= '<textarea class="flat" cols="60" name="value1">';
 		$texte.=$conf->global->PROPALE_ADDON_PDF_ODT_PATH;
 		$texte.= '</textarea>';
-        $texte.= '</td>';
+		$texte.= '</td>';
 		$texte.= '<td align="center">&nbsp; ';
-        $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
-        $texte.= '</td>';
+		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
+		$texte.= '</td>';
 		$texte.= '</tr>';
-        $texte.= '</table>';
+		$texte.= '</table>';
 
 		// Scan directories
 		if (count($listofdir))
@@ -190,7 +192,7 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 		$texte.= '</tr>';
 
 		/*$texte.= '<tr>';
-		$texte.= '<td align="center">';
+		 $texte.= '<td align="center">';
 		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
 		$texte.= '</td>';
 		$texte.= '</tr>';*/
@@ -207,9 +209,9 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 	 *	@param		Propale		$object				Object source to build document
 	 *	@param		Translate	$outputlangs		Lang output object
 	 * 	@param		string		$srctemplatepath	Full path of source filename for generator using a template file
-     *  @param		int			$hidedetails		Do not show line details
-     *  @param		int			$hidedesc			Do not show desc
-     *  @param		int			$hideref			Do not show ref
+	 *  @param		int			$hidedetails		Do not show line details
+	 *  @param		int			$hidedesc			Do not show desc
+	 *  @param		int			$hideref			Do not show ref
 	 *	@return		int         					1 if OK, <=0 if KO
 	 */
 	function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
@@ -222,14 +224,14 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 			return -1;
 		}
 
-                // Add odtgeneration hook
-                if (! is_object($hookmanager))
-                {
-                        include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-                        $hookmanager=new HookManager($this->db);
-                }
-                $hookmanager->initHooks(array('odtgeneration'));
-                global $action;
+		// Add odtgeneration hook
+		if (! is_object($hookmanager))
+		{
+			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			$hookmanager=new HookManager($this->db);
+		}
+		$hookmanager->initHooks(array('odtgeneration'));
+		global $action;
 
 		if (! is_object($outputlangs)) $outputlangs=$langs;
 		$sav_charset_output=$outputlangs->charset_output;
@@ -276,7 +278,7 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 				$newfiletmp=preg_replace('/\.odt/i','',$newfile);
 				$newfiletmp=preg_replace('/template_/i','',$newfiletmp);
 				$newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
-			    $newfiletmp=$objectref.'_'.$newfiletmp;
+				$newfiletmp=$objectref.'_'.$newfiletmp;
 				//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
 				$file=$dir.'/'.$newfiletmp.'.odt';
 				//print "newdir=".$dir;
@@ -287,64 +289,64 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 				dol_mkdir($conf->propal->dir_temp);
 
 
-                // If BILLING contact defined on invoice, we use it
-                $usecontact=false;
-                $arrayidcontact=$object->getIdContact('external','BILLING');
-                if (count($arrayidcontact) > 0)
-                {
-                    $usecontact=true;
-                    $result=$object->fetch_contact($arrayidcontact[0]);
-                }
-
-                // Recipient name
-                if (! empty($usecontact))
-                {
-                    // On peut utiliser le nom de la societe du contact
-                    if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
-                    else $socobject = $object->client;
-                }
-                else
-                {
-                    $socobject=$object->client;
-                }
-
-                // Make substitution
-                $substitutionarray=array(
-                    '__FROM_NAME__' => $this->emetteur->nom,
-                    '__FROM_EMAIL__' => $this->emetteur->email,
-                    '__TOTAL_TTC__' => $object->total_ttc,
-                    '__TOTAL_HT__' => $object->total_ht,
-                    '__TOTAL_VAT__' => $object->total_vat
-                );
-                complete_substitutions_array($substitutionarray, $langs, $object);
-                // Call the ODTSubstitution hook
-                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
-                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+				// If BILLING contact defined on invoice, we use it
+				$usecontact=false;
+				$arrayidcontact=$object->getIdContact('external','BILLING');
+				if (count($arrayidcontact) > 0)
+				{
+					$usecontact=true;
+					$result=$object->fetch_contact($arrayidcontact[0]);
+				}
+
+				// Recipient name
+				if (! empty($usecontact))
+				{
+					// On peut utiliser le nom de la societe du contact
+					if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
+					else $socobject = $object->client;
+				}
+				else
+				{
+					$socobject=$object->client;
+				}
+
+				// Make substitution
+				$substitutionarray=array(
+				'__FROM_NAME__' => $this->emetteur->nom,
+				'__FROM_EMAIL__' => $this->emetteur->email,
+				'__TOTAL_TTC__' => $object->total_ttc,
+				'__TOTAL_HT__' => $object->total_ht,
+				'__TOTAL_VAT__' => $object->total_vat
+				);
+				complete_substitutions_array($substitutionarray, $langs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
 				// Line of free text
 				$newfreetext='';
 				$paramfreetext='PROPALE_FREE_TEXT';
-			    if (! empty($conf->global->$paramfreetext))
-			    {
-			        $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
-			    }
+				if (! empty($conf->global->$paramfreetext))
+				{
+					$newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
+				}
 
-                // Open and load template
+				// Open and load template
 				require_once ODTPHP_PATH.'odf.php';
 				$odfHandler = new odf(
-				    $srctemplatepath,
-				    array(
-						'PATH_TO_TMP'	  => $conf->propal->dir_temp,
-						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
-						'DELIMITER_LEFT'  => '{',
-						'DELIMITER_RIGHT' => '}'
+					$srctemplatepath,
+					array(
+					'PATH_TO_TMP'	  => $conf->propal->dir_temp,
+					'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
+					'DELIMITER_LEFT'  => '{',
+					'DELIMITER_RIGHT' => '}'
 					)
 				);
 				// After construction $odfHandler->contentXml contains content and
 				// [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
 				// [!-- BEGIN lines --]*[!-- END lines --]
-                //print html_entity_decode($odfHandler->__toString());
-                //print exit;
+				//print html_entity_decode($odfHandler->__toString());
+				//print exit;
 
 
 				// Make substitutions into odt of freetext
@@ -355,29 +357,29 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 				{
 				}
 
-                // Make substitutions into odt of user info
+				// Make substitutions into odt of user info
 				$tmparray=$this->get_substitutionarray_user($user,$outputlangs);
-                //var_dump($tmparray); exit;
-                foreach($tmparray as $key=>$value)
-                {
-                    try {
-                        if (preg_match('/logo$/',$key)) // Image
-                        {
-                            //var_dump($value);exit;
-                            if (file_exists($value)) $odfHandler->setImage($key, $value);
-                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
-                        }
-                        else    // Text
-                        {
-                            $odfHandler->setVars($key, $value, true, 'UTF-8');
-                        }
-                    }
-                    catch(OdfException $e)
-                    {
-                    }
-                }
-                // Make substitutions into odt of mysoc
-                $tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
+				//var_dump($tmparray); exit;
+				foreach($tmparray as $key=>$value)
+				{
+					try {
+						if (preg_match('/logo$/',$key)) // Image
+						{
+							//var_dump($value);exit;
+							if (file_exists($value)) $odfHandler->setImage($key, $value);
+							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
+						}
+						else    // Text
+						{
+							$odfHandler->setVars($key, $value, true, 'UTF-8');
+						}
+					}
+					catch(OdfException $e)
+					{
+					}
+				}
+				// Make substitutions into odt of mysoc
+				$tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
 				//var_dump($tmparray); exit;
 				foreach($tmparray as $key=>$value)
 				{
@@ -397,7 +399,7 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 					{
 					}
 				}
-                // Make substitutions into odt of thirdparty
+				// Make substitutions into odt of thirdparty
 				$tmparray=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
 				foreach($tmparray as $key=>$value)
 				{
@@ -417,74 +419,74 @@ class doc_generic_proposal_odt extends ModelePDFPropales
 					}
 				}
 				// Replace tags of object + external modules
-			    $tmparray=$this->get_substitutionarray_propal($object,$outputlangs);
-			    //print_r($tmparray); exit;
-			    complete_substitutions_array($tmparray, $outputlangs, $object);
-                                // Call the ODTSubstitution hook
-                                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-                                $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-                foreach($tmparray as $key=>$value)
-                {
-                    try {
-                        if (preg_match('/logo$/',$key)) // Image
-                        {
-                            if (file_exists($value)) $odfHandler->setImage($key, $value);
-                            else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
-                        }
-                        else    // Text
-                        {
-                            $odfHandler->setVars($key, $value, true, 'UTF-8');
-                        }
-                    }
-                    catch(OdfException $e)
-                    {
-                    }
-                }
+				$tmparray=$this->get_substitutionarray_propal($object,$outputlangs);
+				//print_r($tmparray); exit;
+				complete_substitutions_array($tmparray, $outputlangs, $object);
+				// Call the ODTSubstitution hook
+				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
+				$reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+				foreach($tmparray as $key=>$value)
+				{
+					try {
+						if (preg_match('/logo$/',$key)) // Image
+						{
+							if (file_exists($value)) $odfHandler->setImage($key, $value);
+							else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
+						}
+						else    // Text
+						{
+							$odfHandler->setVars($key, $value, true, 'UTF-8');
+						}
+					}
+					catch(OdfException $e)
+					{
+					}
+				}
 				// Replace tags of lines
-                try
-                {
-                    $listlines = $odfHandler->setSegment('lines');
-                    foreach ($object->lines as $line)
-                    {
-                        $tmparray=$this->get_substitutionarray_propal_lines($line,$outputlangs);
-                        complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
-                        // Call the ODTSubstitutionLine hook
-                        $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
-                        $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
-                        foreach($tmparray as $key => $val)
-                        {
-                             try
-                             {
-                                $listlines->setVars($key, $val, true, 'UTF-8');
-                             }
-                             catch(OdfException $e)
-                             {
-                             }
-                             catch(SegmentException $e)
-                             {
-                             }
-                        }
-                        $listlines->merge();
-                    }
-                    $odfHandler->mergeSegment($listlines);
-                }
-                catch(OdfException $e)
-                {
-                    $this->error=$e->getMessage();
-                    dol_syslog($this->error, LOG_WARNING);
-                    return -1;
-                }
-
-                                // Call the beforeODTSave hook
+				try
+				{
+					$listlines = $odfHandler->setSegment('lines');
+					foreach ($object->lines as $line)
+					{
+						$tmparray=$this->get_substitutionarray_propal_lines($line,$outputlangs);
+						complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
+						// Call the ODTSubstitutionLine hook
+						$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
+						$reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
+						foreach($tmparray as $key => $val)
+						{
+							try
+							{
+								$listlines->setVars($key, $val, true, 'UTF-8');
+							}
+							catch(OdfException $e)
+							{
+							}
+							catch(SegmentException $e)
+							{
+							}
+						}
+						$listlines->merge();
+					}
+					$odfHandler->mergeSegment($listlines);
+				}
+				catch(OdfException $e)
+				{
+					$this->error=$e->getMessage();
+					dol_syslog($this->error, LOG_WARNING);
+					return -1;
+				}
+
+				// Call the beforeODTSave hook
 				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
 				$reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
 
-                // Write new file
+				// Write new file
 				//$result=$odfHandler->exportAsAttachedFile('toto');
 				$odfHandler->saveToDisk($file);
 
 				if (! empty($conf->global->MAIN_UMASK))
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
+					@chmod($file, octdec($conf->global->MAIN_UMASK));
 
 				$odfHandler=null;	// Destroy object
 
diff --git a/htdocs/core/tpl/notes.tpl.php b/htdocs/core/tpl/notes.tpl.php
index 1fb10e66fda174d05d166092a9442c3b10af6859..e0acf0489e8db23a4b24f8f30ab873cd919f6ac5 100644
--- a/htdocs/core/tpl/notes.tpl.php
+++ b/htdocs/core/tpl/notes.tpl.php
@@ -1,5 +1,6 @@
 <?php
 /* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -18,19 +19,21 @@
 
 $module = $object->element;
 $note_public = 'note_public';
-$note_private = 'note';
+$note_private = 'note_private';
 
 $colwidth=(isset($colwidth)?$colwidth:25);
 $permission=(isset($permission)?$permission:(isset($user->rights->$module->creer)?$user->rights->$module->creer:0));    // If already defined by caller page
 $moreparam=(isset($moreparam)?$moreparam:'');
 
 // Special cases
-if ($module == 'propal')                 { $permission=$user->rights->propale->creer; }
-elseif ($module == 'fichinter')         { $permission=$user->rights->ficheinter->creer; $note_private = 'note_private'; }
-elseif ($module == 'project')           { $permission=$user->rights->projet->creer; $note_private = 'note_private'; }
-elseif ($module == 'project_task')      { $permission=$user->rights->projet->creer; $note_private = 'note_private'; }
-elseif ($module == 'invoice_supplier')  { $permission=$user->rights->fournisseur->facture->creer; }
-elseif ($module == 'order_supplier')    { $permission=$user->rights->fournisseur->commande->creer; }
+if ($module == 'propal')                 { $permission=$user->rights->propale->creer;}
+elseif ($module == 'fichinter')         { $permission=$user->rights->ficheinter->creer;}
+elseif ($module == 'project')           { $permission=$user->rights->projet->creer;}
+elseif ($module == 'project_task')      { $permission=$user->rights->projet->creer;}
+elseif ($module == 'invoice_supplier')  { $permission=$user->rights->fournisseur->facture->creer;}
+elseif ($module == 'order_supplier')    { $permission=$user->rights->fournisseur->commande->creer;}
+elseif ($module == 'societe')    		{ $permission=$user->rights->societe->creer;}
+elseif ($module == 'shipping')    		{ $permission=$user->rights->expedition->creer;}
 
 if (! empty($conf->global->FCKEDITOR_ENABLE_SOCIETE)) $typeofdata='ckeditor:dolibarr_notes:100%:200::1:12:100';
 else $typeofdata='textarea:12:100';
diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php
index 9896eb50486e4474d6e2c7aca372ae18040f9178..bb6d19aae548185cb9f73f3ed9fc1d43b7b1594f 100644
--- a/htdocs/expedition/class/expedition.class.php
+++ b/htdocs/expedition/class/expedition.class.php
@@ -4,6 +4,7 @@
  * Copyright (C) 2007		Franky Van Liedekerke	<franky.van.liedekerke@telenet.be>
  * Copyright (C) 2006-2012	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2011-2012	Juanjo Menent			<jmenent@2byte.es>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -56,6 +57,8 @@ class Expedition extends CommonObject
 	var $tracking_url;
 	var $statut;
 	var $billed;
+	var $note_public;
+	var $note_private;
 
 	var $trueWeight;
 	var $weight_units;
@@ -191,6 +194,8 @@ class Expedition extends CommonObject
 		$sql.= ", height";
 		$sql.= ", weight_units";
 		$sql.= ", size_units";
+		$sql.= ", note_private";
+		$sql.= ", note_public";
 		$sql.= ") VALUES (";
 		$sql.= "'(PROV)'";
 		$sql.= ", ".$conf->entity;
@@ -210,6 +215,8 @@ class Expedition extends CommonObject
 		$sql.= ", ".$this->sizeH;	// TODO Should use this->trueHeight
 		$sql.= ", ".$this->weight_units;
 		$sql.= ", ".$this->size_units;
+		$sql.= ", ".(!empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
+		$sql.= ", ".(!empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
 		$sql.= ")";
 
 		$resql=$this->db->query($sql);
@@ -339,8 +346,9 @@ class Expedition extends CommonObject
 		$sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut";
 		$sql.= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
 		$sql.= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
-		$sql.= ", e.fk_expedition_methode, e.tracking_number";
+		$sql.= ", e.fk_shipping_method, e.tracking_number";
 		$sql.= ", el.fk_source as origin_id, el.sourcetype as origin";
+		$sql.= ", e.note_private, e.note_public";
 		$sql.= " FROM ".MAIN_DB_PREFIX."expedition as e";
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->element."'";
 		$sql.= " WHERE e.entity = ".$conf->entity;
@@ -387,6 +395,9 @@ class Expedition extends CommonObject
 				$this->height_units         = $obj->size_units;
 				$this->trueDepth            = $obj->size;
 				$this->depth_units          = $obj->size_units;
+				
+				$this->note_public          = $obj->note_public;
+				$this->note_private         = $obj->note_private;
 
 				// A denormalized value
 				$this->trueSize           	= $obj->size."x".$obj->width."x".$obj->height;
@@ -690,7 +701,8 @@ class Expedition extends CommonObject
 		if (isset($this->size_units)) $this->size_units=trim($this->size_units);
 		if (isset($this->weight_units)) $this->weight_units=trim($this->weight_units);
 		if (isset($this->trueWeight)) $this->weight=trim($this->trueWeight);
-		if (isset($this->note)) $this->note=trim($this->note);
+		if (isset($this->note_private)) $this->note=trim($this->note_private);
+		if (isset($this->note_public)) $this->note=trim($this->note_public);
 		if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
 
 
@@ -721,7 +733,8 @@ class Expedition extends CommonObject
 		$sql.= " size=".(($this->trueDepth != '')?$this->trueDepth:"null").",";
 		$sql.= " weight_units=".(isset($this->weight_units)?$this->weight_units:"null").",";
 		$sql.= " weight=".(($this->trueWeight != '')?$this->trueWeight:"null").",";
-		$sql.= " note=".(isset($this->note)?"'".$this->db->escape($this->note)."'":"null").",";
+		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
+		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
 		$sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
 		$sql.= " entity=".$conf->entity;
 
@@ -1093,6 +1106,9 @@ class Expedition extends CommonObject
 
         $this->origin_id            = 1;
         $this->origin               = 'commande';
+        
+        $this->note_private			= 'Private note';
+        $this->note_public			= 'Public note';
 
 		$nbp = 5;
 		$xnbp = 0;
diff --git a/htdocs/expedition/fiche.php b/htdocs/expedition/fiche.php
index 390e40810660d0a499f8c33ef8089b793e688da1..51d19ff2fa6c25d32a2b3fa0d2cb8251e6b34365 100644
--- a/htdocs/expedition/fiche.php
+++ b/htdocs/expedition/fiche.php
@@ -4,6 +4,7 @@
  * Copyright (C) 2005		Simon TOSSER			<simon@kornog-computing.com>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2011-2012	Juanjo Menent			<jmenent@2byte.es>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -32,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/sendings.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 if (! empty($conf->product->enabled) || ! empty($conf->service->enabled))  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 if (! empty($conf->propal->enabled))   require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
 if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
@@ -107,6 +109,8 @@ if ($action == 'add')
     $object->shipping_method_id		= GETPOST('shipping_method_id','int');
     $object->tracking_number		= GETPOST('tracking_number','alpha');
     $object->ref_int				= GETPOST('ref_int','alpha');
+    $object->note_private			= GETPOST('note_private');
+    $object->note_public			= GETPOST('note_public');
 
     $num=count($objectsrc->lines);
     $totalqty=0;
@@ -629,12 +633,22 @@ if ($action == 'create')
             print $form->select_date($object->date_livraison?$object->date_livraison:-1,'date_delivery',1,1);
             print "</td>\n";
             print '</tr>';
+            
+            // Note Public  
+            print '<tr><td>'.$langs->trans("NotePublic").'</td>';
+            print '<td colspan="3">';
+            $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);
+            print "</td></tr>";
 
-            // Note
-            if ($object->note && ! $user->societe_id)
+            // Note Private
+            if ($object->note_private && ! $user->societe_id)
             {
                 print '<tr><td>'.$langs->trans("NotePrivate").'</td>';
-                print '<td colspan="3">'.nl2br($object->note)."</td></tr>";
+                print '<td colspan="3">';
+                $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+        		print $doleditor->Create(1);	
+                print "</td></tr>";
             }
 
             // Weight
diff --git a/htdocs/expedition/note.php b/htdocs/expedition/note.php
new file mode 100644
index 0000000000000000000000000000000000000000..2fcd18fef130f67c6b1bb1181e24e593d850d55c
--- /dev/null
+++ b/htdocs/expedition/note.php
@@ -0,0 +1,160 @@
+<?php
+/* Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
+ * Copyright (C) 2004-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
+* Copyright (C) 2005-2012  Regis Houssin        <regis.houssin@capnetworks.com>
+* Copyright (C) 2013 	   Florian Henry        <florian.henry@open-concept.pro>
+*
+* 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
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ *      \file       htdocs/expedition/note.php
+*      \ingroup    expedition
+*      \brief      Note card expedition
+*/
+
+error_reporting(E_ALL);
+ini_set('display_errors', true);
+ini_set('html_errors', false);
+
+require '../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/sendings.lib.php';
+
+$langs->load("sendings");
+$langs->load("companies");
+$langs->load("bills");
+$langs->load('deliveries');
+$langs->load('orders');
+$langs->load('stocks');
+$langs->load('other');
+$langs->load('propal');
+
+$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int'));  // For backward compatibility
+$ref=GETPOST('ref','alpha');
+$action=GETPOST('action','alpha');
+
+// Security check
+$socid='';
+if ($user->societe_id) $socid=$user->societe_id;
+$result=restrictedArea($user, $origin, $origin_id);
+
+$object = new Expedition($db);
+$object->fetch($id);
+
+
+/******************************************************************************/
+/*                     Actions                                                */
+/******************************************************************************/
+
+if ($action == 'setnote_public' && $user->rights->facture->creer)
+{
+	$object->fetch($id);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
+	if ($result < 0) dol_print_error($db,$object->error);
+}
+
+else if ($action == 'setnote_private' && $user->rights->facture->creer)
+{
+	$object->fetch($id);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
+	if ($result < 0) dol_print_error($db,$object->error);
+}
+
+
+/******************************************************************************/
+/* Affichage fiche                                                            */
+/******************************************************************************/
+
+llxHeader();
+
+$form = new Form($db);
+
+if ($id > 0 || ! empty($ref))
+{
+
+	$soc = new Societe($db);
+	$soc->fetch($object->socid);
+
+	$head=shipping_prepare_head($object);
+    dol_fiche_head($head, 'note', $langs->trans("Sending"), 0, 'sending');
+
+	print '<table class="border" width="100%">';
+
+	$linkback = '<a href="'.DOL_URL_ROOT.'/expedition/liste.php">'.$langs->trans("BackToList").'</a>';
+
+	// Ref
+	print '<tr><td width="20%">'.$langs->trans("Ref").'</td>';
+	print '<td colspan="3">';
+	print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref');
+	print '</td></tr>';
+
+	// Customer
+	print '<tr><td width="20%">'.$langs->trans("Customer").'</td>';
+	print '<td colspan="3">'.$soc->getNomUrl(1).'</td>';
+	print "</tr>";
+
+	// Linked documents
+	if ($typeobject == 'commande' && $object->$typeobject->id && ! empty($conf->commande->enabled))
+	{
+		print '<tr><td>';
+		$objectsrc=new Commande($db);
+		$objectsrc->fetch($object->$typeobject->id);
+		print $langs->trans("RefOrder").'</td>';
+		print '<td colspan="3">';
+		print $objectsrc->getNomUrl(1,'commande');
+		print "</td>\n";
+		print '</tr>';
+	}
+	if ($typeobject == 'propal' && $object->$typeobject->id && ! empty($conf->propal->enabled))
+	{
+		print '<tr><td>';
+		$objectsrc=new Propal($db);
+		$objectsrc->fetch($object->$typeobject->id);
+		print $langs->trans("RefProposal").'</td>';
+		print '<td colspan="3">';
+		print $objectsrc->getNomUrl(1,'expedition');
+		print "</td>\n";
+		print '</tr>';
+	}
+
+	// Ref customer
+	print '<tr><td>'.$langs->trans("RefCustomer").'</td>';
+	print '<td colspan="3">'.$object->ref_customer."</a></td>\n";
+	print '</tr>';
+
+	// Date creation
+	print '<tr><td>'.$langs->trans("DateCreation").'</td>';
+	print '<td colspan="3">'.dol_print_date($object->date_creation,"day")."</td>\n";
+	print '</tr>';
+
+	// Delivery date planed
+	print '<tr><td>'.$langs->trans("DateDeliveryPlanned").'</td>';
+	print '<td colspan="3">'.dol_print_date($object->date_delivery,"dayhourtext")."</td>\n";
+	print '</tr>';
+
+	print '</table>';
+
+	print '<br>';
+
+	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
+
+	dol_fiche_end();
+}
+
+
+llxFooter();
+
+$db->close();
+?>
diff --git a/htdocs/fichinter/fiche.php b/htdocs/fichinter/fiche.php
index e355ebd0c962e9ab55a25f7a29ba488a8731af64..4e8b9e2b1d82205588218be1ca9b42ea053d5cbd 100644
--- a/htdocs/fichinter/fiche.php
+++ b/htdocs/fichinter/fiche.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2012	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2011-2013  Juanjo Menent			<jmenent@2byte.es>
+ * Copyright (C) 2013       Florian Henry        <florian.henry@open-concept.pro>
  *
  * 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
@@ -39,6 +40,7 @@ if (! empty($conf->global->FICHEINTER_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."
 {
     require_once DOL_DOCUMENT_ROOT ."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.'.php';
 }
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 $langs->load("companies");
 $langs->load("interventions");
@@ -378,7 +380,7 @@ else if ($action == 'setdescription' && $user->rights->ficheinter->creer)
 else if ($action == 'setnote_public' && $user->rights->ficheinter->creer)
 {
     $object->fetch($id);
-    $result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+    $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
     if ($result < 0) dol_print_error($db,$object->error);
 }
 else if ($action == 'setnote_private' && $user->rights->ficheinter->creer)
@@ -977,16 +979,20 @@ if ($action == 'create')
         print '<tr>';
         print '<td class="border" valign="top">'.$langs->trans('NotePublic').'</td>';
         print '<td valign="top" colspan="2">';
-        print '<textarea name="note_public" cols="80" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
+        $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+        print $doleditor->Create(1);
+        //print '<textarea name="note_public" cols="80" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
         print '</td></tr>';
 
         // Private note
-        if (! $user->societe_id)
+        if (!empty($user->societe_id))
         {
         	print '<tr>';
         	print '<td class="border" valign="top">'.$langs->trans('NotePrivate').'</td>';
         	print '<td valign="top" colspan="2">';
-        	print '<textarea name="note_private" cols="80" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
+        	$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+        	print $doleditor->Create(1);
+        	//print '<textarea name="note_private" cols="80" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
         	print '</td></tr>';
         }
 
diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php
index 054933139d8d7b0b4ba8bc621326d5bb4f82e74b..3b7e8b5c96023a1a0ea1307004a755ce903feaf1 100644
--- a/htdocs/fichinter/note.php
+++ b/htdocs/fichinter/note.php
@@ -1,6 +1,7 @@
 <?php
 /* Copyright (C) 2005-2012	Regis Houssin	<regis.houssin@capnetworks.com>
  * Copyright (C) 2011-2012	Juanjo Menent	<jmenent@2byte.es>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -47,13 +48,13 @@ $object->fetch($id,$ref);
 
 if ($action == 'setnote_public' && $user->rights->ficheinter->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
 else if ($action == 'setnote_private' && $user->rights->ficheinter->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php
index 99a443c71db8455ea212743f2825fd809b3d5f15..2c6ad45f30fcfb4b8f8c4a9e930405284b4498bd 100644
--- a/htdocs/fourn/class/fournisseur.commande.class.php
+++ b/htdocs/fourn/class/fournisseur.commande.class.php
@@ -6,6 +6,7 @@
  * Copyright (C) 2010-2013	Juanjo Menent			<jmenent@2byte.es>
  * Copyright (C) 2010-2013	Philippe Grand			<philippe.grand@atoo-net.com>
  * Copyright (C) 2012       Marcos García           <marcosgdf@gmail.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -121,7 +122,7 @@ class CommandeFournisseur extends CommonOrder
         $sql.= " c.date_creation, c.date_valid, c.date_approve,";
         $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve,";
         $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,";
-        $sql.= " c.note as note_private, c.note_public, c.model_pdf, c.extraparams,";
+        $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams,";
         $sql.= " cm.libelle as methode_commande,";
         $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
         $sql.= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle";
@@ -602,7 +603,7 @@ class CommandeFournisseur extends CommonOrder
 
     /**
      *  Renvoie la reference de commande suivante non utilisee en fonction du modele
-     *                  de numerotation actif defini dans COMMANDE_SUPPLIER_ADDON
+     *                  de numerotation actif defini dans COMMANDE_SUPPLIER_ADDON_NUMBER
      *
      *  @param	    Societe		$soc  		objet societe
      *  @return     string                  reference libre pour la facture
@@ -614,14 +615,14 @@ class CommandeFournisseur extends CommonOrder
 
         $dir = DOL_DOCUMENT_ROOT .'/core/modules/supplier_order/';
 
-        if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON))
+        if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
         {
-            $file = $conf->global->COMMANDE_SUPPLIER_ADDON.'.php';
+            $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
 
             if (is_readable($dir.'/'.$file))
             {
                 // Definition du nom de modele de numerotation de commande fournisseur
-                $modName=$conf->global->COMMANDE_SUPPLIER_ADDON;
+                $modName=$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
                 require_once $dir.'/'.$file;
 
                 // Recuperation de la nouvelle reference
@@ -642,7 +643,7 @@ class CommandeFournisseur extends CommonOrder
             }
             else
             {
-                print $langs->trans("Error")." ".$langs->trans("Error_FailedToLoad_COMMANDE_SUPPLIER_ADDON_File",$conf->global->COMMANDE_SUPPLIER_ADDON);
+                print $langs->trans("Error")." ".$langs->trans("Error_FailedToLoad_COMMANDE_SUPPLIER_ADDON_File",$conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER);
                 return -2;
             }
         }
@@ -927,7 +928,7 @@ class CommandeFournisseur extends CommonOrder
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
         $sql.= "ref";
         $sql.= ", ref_supplier";
-        $sql.= ", note";
+        $sql.= ", note_private";
         $sql.= ", note_public";
         $sql.= ", entity";
         $sql.= ", fk_soc";
@@ -942,7 +943,7 @@ class CommandeFournisseur extends CommonOrder
         $sql.= " VALUES (";
         $sql.= "''";
         $sql.= ", '".$this->ref_supplier."'";
-        $sql.= ", '".$this->note."'";
+        $sql.= ", '".$this->note_private."'";
         $sql.= ", '".$this->note_public."'";
         $sql.= ", ".$conf->entity;
         $sql.= ", ".$this->socid;
@@ -1874,7 +1875,7 @@ class CommandeFournisseur extends CommonOrder
         $this->cond_reglement_code = 'RECEP';
         $this->mode_reglement_code = 'CHQ';
         $this->note_public='This is a comment (public)';
-        $this->note='This is a comment (private)';
+        $this->note_private='This is a comment (private)';
         // Lines
         $nbp = 5;
         $xnbp = 0;
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index e1d084939acf66ecc95e61338274b6fb3fb27a5e..d3c7d12d98a1bb32c83273ef03c7debffd2b3a57 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -6,6 +6,7 @@
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2010-2011	Juanjo Menent			<jmenent@2byte.es>
  * Copyright (C) 2013		Philippe Grand			<philippe.grand@atoo-net.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -140,7 +141,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= ", fk_soc";
         $sql.= ", datec";
         $sql.= ", datef";
-        $sql.= ", note";
+        $sql.= ", note_private";
         $sql.= ", note_public";
         $sql.= ", fk_user_author";
         $sql.= ", date_lim_reglement";
@@ -153,7 +154,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= ", ".$this->socid;
         $sql.= ", '".$this->db->idate($now)."'";
         $sql.= ", '".$this->db->idate($this->date)."'";
-        $sql.= ", '".$this->db->escape($this->note)."'";
+        $sql.= ", '".$this->db->escape($this->note_private)."'";
         $sql.= ", '".$this->db->escape($this->note_public)."'";
         $sql.= ", ".$user->id.",";
         $sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null";
@@ -297,7 +298,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= " t.fk_projet,";
         $sql.= " t.fk_cond_reglement,";
         $sql.= " t.date_lim_reglement,";
-        $sql.= " t.note as note_private,";
+        $sql.= " t.note_private,";
         $sql.= " t.note_public,";
         $sql.= " t.model_pdf,";
         $sql.= " t.import_key,";
@@ -496,7 +497,7 @@ class FactureFournisseur extends CommonInvoice
         if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
         if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
         if (isset($this->fk_cond_reglement)) $this->fk_cond_reglement=trim($this->fk_cond_reglement);
-        if (isset($this->note)) $this->note=trim($this->note);
+        if (isset($this->note_private)) $this->note=trim($this->note_private);
         if (isset($this->note_public)) $this->note_public=trim($this->note_public);
         if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
         if (isset($this->import_key)) $this->import_key=trim($this->import_key);
@@ -535,7 +536,7 @@ class FactureFournisseur extends CommonInvoice
         $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
         $sql.= " fk_cond_reglement=".(isset($this->fk_cond_reglement)?$this->fk_cond_reglement:"null").",";
         $sql.= " date_lim_reglement=".(dol_strlen($this->date_echeance)!=0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
-        $sql.= " note=".(isset($this->note)?"'".$this->db->escape($this->note)."'":"null").",";
+        $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
         $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
         $sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
         $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
@@ -1433,7 +1434,7 @@ class FactureFournisseur extends CommonInvoice
         $this->cond_reglement_code = 'RECEP';
         $this->mode_reglement_code = 'CHQ';
         $this->note_public='This is a comment (public)';
-        $this->note='This is a comment (private)';
+        $this->note_private='This is a comment (private)';
         // Lines
         $nbp = 5;
         $xnbp = 0;
diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php
index 09843191692b6961d57c86e95aafda7d2ab16d51..9a86f0e9ee330798d5255cb16b1dbfc81a68e0b5 100644
--- a/htdocs/fourn/class/fournisseur.product.class.php
+++ b/htdocs/fourn/class/fournisseur.product.class.php
@@ -146,6 +146,7 @@ class ProductFournisseur extends Product
      *    @param  	string		$charges			costs affering to product
 	 *    @param  	float		$remise_percent		Discount  regarding qty (percent)
 	 *    @param  	float		$remise				Discount  regarding qty (amount)
+	 *    @param  	int			$newnpr				Set NPR or not
      *    @return	int								<0 if KO, >=0 if OK
      */
     function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0)
diff --git a/htdocs/fourn/commande/fiche.php b/htdocs/fourn/commande/fiche.php
index 6ba577c152bf5187875faa0d88a95dedd8ae844d..2be0c23e78b904ce10d9ed40faa0115751a31390 100644
--- a/htdocs/fourn/commande/fiche.php
+++ b/htdocs/fourn/commande/fiche.php
@@ -6,6 +6,7 @@
  * Copyright (C) 2010-2013 Juanjo Menent        <jmenent@2byte.es>
  * Copyright (C) 2011      Philippe Grand       <philippe.grand@atoo-net.com>
  * Copyright (C) 2012      Marcos García        <marcosgdf@gmail.com>
+ * Copyright (C) 2013      Florian Henry        <florian.henry@open-concept.pro>
  *
  * 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
@@ -37,6 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 if (!empty($conf->produit->enabled))
 	require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 if (!empty($conf->projet->enabled))
@@ -138,13 +140,13 @@ else if ($action ==	'setremisepercent' && $user->rights->fournisseur->commande->
 
 else if ($action == 'setnote_public' && $user->rights->fournisseur->commande->creer)
 {
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
-else if ($action == 'setnote' && $user->rights->fournisseur->commande->creer)
+else if ($action == 'setnote_private' && $user->rights->fournisseur->commande->creer)
 {
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
@@ -675,7 +677,7 @@ else if ($action == 'add' && $user->rights->fournisseur->commande->creer)
         // Creation commande
         $object->ref_supplier  	= GETPOST('refsupplier');
         $object->socid         	= $socid;
-        $object->note			= GETPOST('note');
+        $object->note_private	= GETPOST('note_private');
         $object->note_public   	= GETPOST('note_public');
 
         $id = $object->create($user);
@@ -997,15 +999,25 @@ if ($action=="create")
 	print '</tr>';
 
 	print '</td></tr>';
-
-	print '<tr><td>'.$langs->trans('Note').'</td>';
-	print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+	
+	print '<tr><td>'.$langs->trans('NotePublic').'</td>';
+	print '<td>';
+	$doleditor = new DolEditor('note_public', GETPOST('note_public'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+	print $doleditor->Create(1);
+	print '</td>';
+	//print '<textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea>';
 	print '</tr>';
 
-	print '<tr><td>'.$langs->trans('NotePublic').'</td>';
-	print '<td><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+	print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
+	print '<td>';
+	$doleditor = new DolEditor('note_private', GETPOST('note_private'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+	print $doleditor->Create(1);
+	print '</td>';
+	//print '<td><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
 	print '</tr>';
 
+	
+
 	// Other options
     $parameters=array();
     $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
@@ -1504,9 +1516,7 @@ elseif (! empty($object->id))
 				$parameters=array('fk_parent_line'=>$line->fk_parent_line, 'line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i);
 				$reshook=$hookmanager->executeHooks('formEditProductOptions',$parameters,$object,$action);
 			}
-
-			// Description - Editor wysiwyg
-			require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+			
 			$nbrows=ROWS_2;
 			if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
 			$doleditor=new DolEditor('eldesc',$line->description,'',200,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,$nbrows,70);
@@ -1532,8 +1542,6 @@ elseif (! empty($object->id))
 	 */
 	if ($object->statut == 0 && $user->rights->fournisseur->commande->creer && $action <> 'editline')
 	{
-		//WYSIWYG Editor
-		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 		print '<tr class="liste_titre">';
 		print '<td>';
diff --git a/htdocs/fourn/commande/note.php b/htdocs/fourn/commande/note.php
index 63cd69a89a070120daa079fc202b53d84afdb34b..7d4fa0cd4964cc66929dde2ed827a0618ed05d4d 100644
--- a/htdocs/fourn/commande/note.php
+++ b/htdocs/fourn/commande/note.php
@@ -51,7 +51,7 @@ $object->fetch($id, $ref);
 
 if ($action == 'setnote_public' && $user->rights->fournisseur->commande->creer)
 {
-    $result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+    $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
     if ($result < 0) dol_print_error($db,$object->error);
 }
 elseif ($action == 'setnote' && $user->rights->fournisseur->commande->creer)
diff --git a/htdocs/fourn/facture/fiche.php b/htdocs/fourn/facture/fiche.php
index e1ff199de6d92f705bef575a83a0daadb8efcc95..d85bd03e06717f3bb4b48c6071b2d159821a18a1 100644
--- a/htdocs/fourn/facture/fiche.php
+++ b/htdocs/fourn/facture/fiche.php
@@ -6,6 +6,7 @@
  * Copyright (C) 2005-2013	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2010-2012	Juanjo Menent			<jmenent@2byte.es>
  * Copyright (C) 2013		Philippe Grand			<philippe.grand@atoo-net.com>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -35,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
 require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 if (!empty($conf->produit->enabled))
 	require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 if (!empty($conf->projet->enabled))
@@ -209,13 +211,13 @@ elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->factur
 elseif ($action == 'setnote_public' && $user->rights->fournisseur->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
-elseif ($action == 'setnote' && $user->rights->fournisseur->facture->creer)
+elseif ($action == 'setnote_private' && $user->rights->fournisseur->facture->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
@@ -273,7 +275,8 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer)
         $object->libelle       = $_POST['libelle'];
         $object->date          = $datefacture;
         $object->date_echeance = $datedue;
-        $object->note_public   = $_POST['note'];
+        $object->note_public   = GETPOST('note_public');
+        $object->note_private  = GETPOST('note_private');
 
         // If creation from another object of another module
         if ($_POST['origin'] && $_POST['originid'])
@@ -1152,7 +1155,20 @@ if ($action == 'create')
     print '</td></tr>';
 
     print '<tr><td>'.$langs->trans('NotePublic').'</td>';
-    print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+    print '<td>';
+    $doleditor = new DolEditor('note_public', GETPOST('note_public'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+    print $doleditor->Create(1);
+    print '</td>';
+   // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+    print '</tr>';
+    
+    // Private note
+    print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
+    print '<td>';
+    $doleditor = new DolEditor('note_private', GETPOST('note_private'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+    print $doleditor->Create(1);
+    print '</td>';
+    // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
     print '</tr>';
 
     if (is_object($objectsrc))
@@ -1702,8 +1718,6 @@ else
                     $reshook=$hookmanager->executeHooks('formEditProductOptions',$parameters,$object,$action);
                 }
 
-                // Description - Editor wysiwyg
-                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
                 $nbrows=ROWS_2;
                 if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
                 $doleditor=new DolEditor('desc',$object->lines[$i]->description,'',128,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,$nbrows,70);
@@ -1849,8 +1863,6 @@ else
                 $reshook=$hookmanager->executeHooks('formCreateSupplierProductOptions',$parameters,$object,$action);
             }
 
-            // Editor wysiwyg
-            require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
             $nbrows=ROWS_2;
             if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
             $doleditor=new DolEditor('dp_desc',GETPOST("dp_desc"),'',100,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,$nbrows,70);
diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php
index bbdd1b5f60fe3a7654e859c955a740dd8c8a7c95..116d0ce1c8be04683839af7b5e6892237ab400fa 100644
--- a/htdocs/fourn/facture/note.php
+++ b/htdocs/fourn/facture/note.php
@@ -2,26 +2,27 @@
 /* Copyright (C) 2004		Rodolphe Quiedeville	<rodolphe@quiedeville.org>
  * Copyright (C) 2004-2011	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.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
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
 
 /**
  *      \file       htdocs/fourn/facture/note.php
  *      \ingroup    facture
- *      \brief      Fiche de notes sur une facture fournisseur
- */
+*      \brief      Fiche de notes sur une facture fournisseur
+*/
 
 require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
@@ -50,21 +51,21 @@ $object->fetch($id,$ref);
 
 if ($action == 'setnote_public' && $user->rights->fournisseur->facture->creer)
 {
-    $result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
-    if ($result < 0) dol_print_error($db,$object->error);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
+	if ($result < 0) dol_print_error($db,$object->error);
 }
-elseif ($action == 'setnote' && $user->rights->fournisseur->facture->creer)
+elseif ($action == 'setnote_private' && $user->rights->fournisseur->facture->creer)
 {
-    $result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
-    if ($result < 0) dol_print_error($db,$object->error);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
+	if ($result < 0) dol_print_error($db,$object->error);
 }
 
 // Set label
 if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer)
 {
-    $object->label=$_POST['label'];
-    $result=$object->update($user);
-    if ($result < 0) dol_print_error($db);
+	$object->label=$_POST['label'];
+	$result=$object->update($user);
+	if ($result < 0) dol_print_error($db);
 }
 
 
@@ -78,82 +79,82 @@ llxHeader();
 
 if ($id)
 {
-    $object->fetch_thirdparty();
-
-    $head = facturefourn_prepare_head($object);
-    $titre=$langs->trans('SupplierInvoice');
-    dol_fiche_head($head, 'note', $titre, 0, 'bill');
-
-
-    print '<table class="border" width="100%">';
-
-    $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
-
-    // Ref
-    print '<tr><td width="20%" nowrap="nowrap">'.$langs->trans("Ref").'</td><td colspan="3">';
-    print $form->showrefnav($object, 'facid', $linkback, 1, 'rowid', 'ref', $morehtmlref);
-    print '</td>';
-    print "</tr>\n";
-
-    // Ref supplier
-    print '<tr><td nowrap="nowrap">'.$langs->trans("RefSupplier").'</td><td colspan="3">'.$object->ref_supplier.'</td>';
-    print "</tr>\n";
-
-    // Company
-    print '<tr><td>'.$langs->trans('Supplier').'</td><td colspan="3">'.$object->thirdparty->getNomUrl(1).'</td></tr>';
-
-    // Type
-    print '<tr><td>'.$langs->trans('Type').'</td><td colspan="4">';
-    print $object->getLibType();
-    if ($object->type == 1)
-    {
-        $facreplaced=new FactureFournisseur($db);
-        $facreplaced->fetch($object->fk_facture_source);
-        print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
-    }
-    if ($object->type == 2)
-    {
-        $facusing=new FactureFournisseur($db);
-        $facusing->fetch($object->fk_facture_source);
-        print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
-    }
-
-    $facidavoir=$object->getListIdAvoirFromInvoice();
-    if (count($facidavoir) > 0)
-    {
-        print ' ('.$langs->transnoentities("InvoiceHasAvoir");
-        $i=0;
-        foreach($facidavoir as $fid)
-        {
-            if ($i==0) print ' ';
-            else print ',';
-            $facavoir=new FactureFournisseur($db);
-            $facavoir->fetch($fid);
-            print $facavoir->getNomUrl(1);
-        }
-        print ')';
-    }
-    if ($facidnext > 0)
-    {
-        $facthatreplace=new FactureFournisseur($db);
-        $facthatreplace->fetch($facidnext);
-        print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
-    }
-    print '</td></tr>';
-
-    // Label
-    print '<tr><td>'.$form->editfieldkey("Label",'label',$object->label,$object,0).'</td><td colspan="3">';
-    print $form->editfieldval("Label",'label',$object->label,$object,0);
-    print '</td>';
-
-    print "</table>";
-
-    print '<br>';
-
-    $colwidth=20;
-    include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
-
-    dol_fiche_end();
+	$object->fetch_thirdparty();
+
+	$head = facturefourn_prepare_head($object);
+	$titre=$langs->trans('SupplierInvoice');
+	dol_fiche_head($head, 'note', $titre, 0, 'bill');
+
+
+	print '<table class="border" width="100%">';
+
+	$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+
+	// Ref
+	print '<tr><td width="20%" nowrap="nowrap">'.$langs->trans("Ref").'</td><td colspan="3">';
+	print $form->showrefnav($object, 'facid', $linkback, 1, 'rowid', 'ref', $morehtmlref);
+	print '</td>';
+	print "</tr>\n";
+
+	// Ref supplier
+	print '<tr><td nowrap="nowrap">'.$langs->trans("RefSupplier").'</td><td colspan="3">'.$object->ref_supplier.'</td>';
+	print "</tr>\n";
+
+	// Company
+	print '<tr><td>'.$langs->trans('Supplier').'</td><td colspan="3">'.$object->thirdparty->getNomUrl(1).'</td></tr>';
+
+	// Type
+	print '<tr><td>'.$langs->trans('Type').'</td><td colspan="4">';
+	print $object->getLibType();
+	if ($object->type == 1)
+	{
+		$facreplaced=new FactureFournisseur($db);
+		$facreplaced->fetch($object->fk_facture_source);
+		print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
+	}
+	if ($object->type == 2)
+	{
+		$facusing=new FactureFournisseur($db);
+		$facusing->fetch($object->fk_facture_source);
+		print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
+	}
+
+	$facidavoir=$object->getListIdAvoirFromInvoice();
+	if (count($facidavoir) > 0)
+	{
+		print ' ('.$langs->transnoentities("InvoiceHasAvoir");
+		$i=0;
+		foreach($facidavoir as $fid)
+		{
+			if ($i==0) print ' ';
+			else print ',';
+			$facavoir=new FactureFournisseur($db);
+			$facavoir->fetch($fid);
+			print $facavoir->getNomUrl(1);
+		}
+		print ')';
+	}
+	if ($facidnext > 0)
+	{
+		$facthatreplace=new FactureFournisseur($db);
+		$facthatreplace->fetch($facidnext);
+		print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
+	}
+	print '</td></tr>';
+
+	// Label
+	print '<tr><td>'.$form->editfieldkey("Label",'label',$object->label,$object,0).'</td><td colspan="3">';
+	print $form->editfieldval("Label",'label',$object->label,$object,0);
+	print '</td>';
+
+	print "</table>";
+
+	print '<br>';
+
+	$colwidth=20;
+	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
+
+	dol_fiche_end();
 }
 
 
diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php
index 8dfaf85ac71ebdfe87384380de05d6b4584916b7..a861496cb726ffe5098f234fdd0c329dd51e54c1 100644
--- a/htdocs/holiday/class/holiday.class.php
+++ b/htdocs/holiday/class/holiday.class.php
@@ -2,6 +2,7 @@
 /* Copyright (C) 2011	Dimitri Mouillard	<dmouillard@teclib.com>
  * Copyright (C) 2012	Laurent Destailleur	<eldy@users.sourceforge.net>
  * Copyright (C) 2012	Regis Houssin		<regis.houssin@capnetworks.com>
+ * Copyright (C) 2013   Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -192,7 +193,7 @@ class Holiday extends CommonObject
         $sql.= " cp.date_cancel,";
         $sql.= " cp.fk_user_cancel,";
         $sql.= " cp.detail_refuse,";
-        $sql.= " cp.note,";
+        $sql.= " cp.note_private,";
         $sql.= " cp.note_public";
         $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp";
         $sql.= " WHERE cp.rowid = ".$id;
@@ -223,7 +224,7 @@ class Holiday extends CommonObject
                 $this->date_cancel = $this->db->jdate($obj->date_cancel);
                 $this->fk_user_cancel = $obj->fk_user_cancel;
                 $this->detail_refuse = $obj->detail_refuse;
-                $this->note = $obj->note;
+                $this->note_private = $obj->note_private;
                 $this->note_public = $obj->note_public;
             }
             $this->db->free($resql);
diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php
index 2d5c991fb77cd14fb7532ca24f9474556a43bfee..7e72eb6f7e24e6107a0ef285e874f38bcb58b7b7 100644
--- a/htdocs/includes/odtphp/odf.php
+++ b/htdocs/includes/odtphp/odf.php
@@ -1,6 +1,4 @@
 <?php
-require_once 'zip/PclZipProxy.php';
-require_once 'zip/PhpZipProxy.php';
 require 'Segment.php';
 class OdfException extends Exception
 {}
@@ -129,6 +127,33 @@ class Odf
 			$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
 			return $this;
 		}
+		
+		/**
+		 * Assing a template variable
+		 *
+		 * @param string $key name of the variable within the template
+		 * @param string $value replacement value
+		 * @param bool $encode if true, special XML characters are encoded
+		 * @throws OdfException
+		 * @return odf
+		 */
+		public function setVarsHeadFooter($key, $value, $encode = true, $charset = 'ISO-8859')
+		{
+			$tag = $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT'];
+			// TODO Warning string may be:
+			// <text:span text:style-name="T13">{</text:span><text:span text:style-name="T12">aaa</text:span><text:span text:style-name="T13">}</text:span>
+			// instead of {aaa} so we should enhance this function.
+			//print $key.'-'.$value.'-'.strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']).'<br>';
+			if (strpos($this->stylesXml, $tag) === false && strpos($this->stylesXml , $tag) === false) {
+			//if (strpos($this->contentXml, '">'. $key . '</text;span>') === false) {
+				throw new OdfException("var $key not found in the document");
+				//}
+			}
+			$value = $encode ? htmlspecialchars($value) : $value;
+				$value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
+				$this->vars[$tag] = str_replace("\n", "<text:line-break/>", $value);
+				return $this;
+		}
 
 		/**
 		 * Evaluating php codes inside the ODT and output the buffer (print, echo) inplace of the code
diff --git a/htdocs/install/mysql/migration/3.3.0-3.4.0.sql b/htdocs/install/mysql/migration/3.3.0-3.4.0.sql
index fef019afd87da14a38ae99c5c1cbe936bfe5aa5e..a59b5b7cdf4b77efca5aaa0bea3538cf662f4617 100755
--- a/htdocs/install/mysql/migration/3.3.0-3.4.0.sql
+++ b/htdocs/install/mysql/migration/3.3.0-3.4.0.sql
@@ -26,18 +26,18 @@ create table llx_adherent_type_extrafields
 ) ENGINE=innodb;
 ALTER TABLE llx_adherent_type_extrafields ADD INDEX idx_adherent_type_extrafields (fk_object);
 
-UPDATE llx_const set value='eldy_menu.php' where value='eldy_backoffice.php';
-UPDATE llx_const set value='eldy_menu.php' where value='eldy_frontoffice.php';
-UPDATE llx_const set value='auguria_menu.php' where value='auguria_backoffice.php';
-UPDATE llx_const set value='auguria_menu.php' where value='auguria_frontoffice.php';
-UPDATE llx_const set value='smartphone_menu.php' where value='smartphone_backoffice.php';
-UPDATE llx_const set value='smartphone_menu.php' where value='smartphone_frontoffice.php';
-UPDATE llx_const set name='MAIN_INFO_SOCIETE_ADDRESS' where name='MAIN_INFO_SOCIETE_ADRESSE';
-UPDATE llx_const set name='MAIN_INFO_SOCIETE_TOWN' where name='MAIN_INFO_SOCIETE_VILLE';
-UPDATE llx_const set name='MAIN_INFO_SOCIETE_ZIP' where name='MAIN_INFO_SOCIETE_CP';
-UPDATE llx_const set name='MAIN_INFO_SOCIETE_COUNTRY' where name='MAIN_INFO_SOCIETE_PAYS';
-UPDATE llx_const set name='MAIN_INFO_SOCIETE_STATE' where name='MAIN_INFO_SOCIETE_DEPARTEMENT';
-UPDATE llx_const set name='LIVRAISON_ADDON_NUMBER' where name='LIVRAISON_ADDON';
+UPDATE llx_const set value = __ENCRYPT('eldy_menu.php')__ where __DECRYPT('value')__ = 'eldy_backoffice.php';
+UPDATE llx_const set value = __ENCRYPT('eldy_menu.php')__ where __DECRYPT('value')__ = 'eldy_frontoffice.php';
+UPDATE llx_const set value = __ENCRYPT('auguria_menu.php')__ where __DECRYPT('value')__ = 'auguria_backoffice.php';
+UPDATE llx_const set value = __ENCRYPT('auguria_menu.php')__ where __DECRYPT('value')__ = 'auguria_frontoffice.php';
+UPDATE llx_const set value = __ENCRYPT('smartphone_menu.php')__ where __DECRYPT('value')__ = 'smartphone_backoffice.php';
+UPDATE llx_const set value = __ENCRYPT('smartphone_menu.php')__ where __DECRYPT('value')__ = 'smartphone_frontoffice.php';
+UPDATE llx_const set name = __ENCRYPT('MAIN_INFO_SOCIETE_ADDRESS')__ where __DECRYPT('name')__ = 'MAIN_INFO_SOCIETE_ADRESSE';
+UPDATE llx_const set name = __ENCRYPT('MAIN_INFO_SOCIETE_TOWN')__ where __DECRYPT('name')__ = 'MAIN_INFO_SOCIETE_VILLE';
+UPDATE llx_const set name = __ENCRYPT('MAIN_INFO_SOCIETE_ZIP')__ where __DECRYPT('name')__ = 'MAIN_INFO_SOCIETE_CP';
+UPDATE llx_const set name = __ENCRYPT('MAIN_INFO_SOCIETE_COUNTRY')__ where __DECRYPT('name')__ = 'MAIN_INFO_SOCIETE_PAYS';
+UPDATE llx_const set name = __ENCRYPT('MAIN_INFO_SOCIETE_STATE')__ where __DECRYPT('name')__ = 'MAIN_INFO_SOCIETE_DEPARTEMENT';
+UPDATE llx_const set name = __ENCRYPT('LIVRAISON_ADDON_NUMBER')__ where __DECRYPT('name')__ = 'LIVRAISON_ADDON';
 
 ALTER TABLE llx_user add COLUMN fk_user integer;
 
@@ -204,26 +204,28 @@ CREATE TABLE llx_cronjob
 
 ALTER TABLE llx_societe MODIFY COLUMN zip varchar(25);
 
-ALTER TABLE llx_user ADD COLUMN   address           varchar(255);
-ALTER TABLE llx_user ADD COLUMN   zip               varchar(25);
-ALTER TABLE llx_user ADD COLUMN   town              varchar(50);
-ALTER TABLE llx_user ADD COLUMN   fk_state          integer        DEFAULT 0;
-ALTER TABLE llx_user ADD COLUMN   fk_country        integer        DEFAULT 0;
+ALTER TABLE llx_user ADD COLUMN address           varchar(255);
+ALTER TABLE llx_user ADD COLUMN zip               varchar(25);
+ALTER TABLE llx_user ADD COLUMN town              varchar(50);
+ALTER TABLE llx_user ADD COLUMN fk_state          integer        DEFAULT 0;
+ALTER TABLE llx_user ADD COLUMN fk_country        integer        DEFAULT 0;
+ALTER TABLE llx_user ADD COLUMN color             varchar(6);
+
 ALTER TABLE llx_product_price ADD COLUMN import_key varchar(14) AFTER price_by_qty;
 
 DROP TABLE llx_printer_ipp;
 CREATE TABLE llx_printer_ipp 
 (
-	rowid int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
+	rowid integer AUTO_INCREMENT PRIMARY KEY,
 	tms 	timestamp,
 	datec 	datetime,
 	printer_name text NOT NULL, 
 	printer_location text NOT NULL,
 	printer_uri varchar(256) NOT NULL,
-	copy int(11) NOT NULL DEFAULT '1',
+	copy integer NOT NULL DEFAULT '1',
 	module varchar(16) NOT NULL,
 	login varchar(32) NOT NULL
-)ENGINE=innodb;
+) ENGINE=innodb;
 
 ALTER TABLE llx_socpeople ADD COLUMN ref_ext varchar(128) after entity;
 
@@ -243,3 +245,21 @@ ALTER TABLE llx_facture_fourn_det ADD COLUMN info_bits integer NOT NULL DEFAULT
 ALTER TABLE llx_actioncomm ADD COLUMN transparency integer after fk_user_action;
 
 INSERT INTO llx_c_action_trigger (rowid,code,label,description,elementtype,rang) VALUES (29,'FICHINTER_SENTBYMAIL','Intervention sent by mail','Executed when a intervention is sent by mail','ficheinter',29);
+
+ALTER TABLE llx_adherent ADD COLUMN canvas varchar(32) after fk_user_valid; 
+
+ALTER TABLE llx_expedition CHANGE COLUMN note note_private text;
+ALTER TABLE llx_expedition ADD COLUMN note_public text after note_private;
+ALTER TABLE llx_livraison CHANGE COLUMN note note_private text;
+ALTER TABLE llx_facture CHANGE COLUMN note note_private text;
+ALTER TABLE llx_commande CHANGE COLUMN note note_private text;
+ALTER TABLE llx_propal CHANGE COLUMN note note_private text;
+ALTER TABLE llx_commande_fournisseur CHANGE COLUMN note note_private text;
+ALTER TABLE llx_contrat CHANGE COLUMN note note_private text;
+ALTER TABLE llx_deplacement CHANGE COLUMN note note_private text;
+ALTER TABLE llx_don CHANGE COLUMN note note_private text;
+ALTER TABLE llx_facture_fourn CHANGE COLUMN note note_private text;
+ALTER TABLE llx_facture_rec CHANGE COLUMN note note_private text;
+ALTER TABLE llx_holiday CHANGE COLUMN note note_private text;
+ALTER TABLE llx_societe CHANGE COLUMN note note_private text;
+ALTER TABLE llx_socpeople CHANGE COLUMN note note_private text;
diff --git a/htdocs/install/mysql/tables/llx_commande.sql b/htdocs/install/mysql/tables/llx_commande.sql
index 0ef0eddb739a36ad965b6f6b7561506a75f30492..325b1f3fe138ceabdb1084a30280b68b9164b8ad 100644
--- a/htdocs/install/mysql/tables/llx_commande.sql
+++ b/htdocs/install/mysql/tables/llx_commande.sql
@@ -50,7 +50,7 @@ create table llx_commande
   localtax2				double(24,8)      default 0,	-- total localtax2
   total_ht				double(24,8)      default 0,
   total_ttc				double(24,8)      default 0,
-  note					text,
+  note_private			text,
   note_public			text,
   model_pdf				varchar(255),
 
diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql
index ac9e49d604f1a4918dd60e80f5dbf8ecee5cbbc0..51e57452397a07dcf732762ff04d72dd7ecc717c 100644
--- a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql
+++ b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql
@@ -50,7 +50,7 @@ create table llx_commande_fournisseur
   localtax2				double(24,8)      default 0,
   total_ht				double(24,8)      default 0,
   total_ttc				double(24,8)      default 0,
-  note					text,
+  note_private			text,
   note_public			text,
   model_pdf				varchar(255),
 
@@ -61,4 +61,4 @@ create table llx_commande_fournisseur
   import_key			varchar(14),
   extraparams			varchar(255)					-- for stock other parameters with json format
   
-)ENGINE=innodb;
\ No newline at end of file
+)ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_contrat.sql b/htdocs/install/mysql/tables/llx_contrat.sql
index e952c8eb073882ff80440e156b3e149f3d6311c8..7521eb0aa1b3821b04efbacd07e94cc8116021bb 100644
--- a/htdocs/install/mysql/tables/llx_contrat.sql
+++ b/htdocs/install/mysql/tables/llx_contrat.sql
@@ -37,7 +37,7 @@ create table llx_contrat
   fk_user_author			integer NOT NULL default 0,
   fk_user_mise_en_service	integer,
   fk_user_cloture			integer,
-  note						text,
+  note_private				text,
   note_public				text,
   import_key				varchar(14),
   extraparams				varchar(255)					-- for stock other parameters with json format
diff --git a/htdocs/install/mysql/tables/llx_deplacement.sql b/htdocs/install/mysql/tables/llx_deplacement.sql
index acf774f41ec0a5ad009882df6e618bd4ccb68c23..34c4ab103cd6c01477e05dbb06a26aaa6a80a024 100644
--- a/htdocs/install/mysql/tables/llx_deplacement.sql
+++ b/htdocs/install/mysql/tables/llx_deplacement.sql
@@ -34,7 +34,7 @@ create table llx_deplacement
   km				real,
   fk_soc			integer,
   fk_projet         integer DEFAULT 0,
-  note				text,
+  note_private	    text,
   note_public       text,
   extraparams		varchar(255)					-- for stock other parameters with json format
   
diff --git a/htdocs/install/mysql/tables/llx_don.sql b/htdocs/install/mysql/tables/llx_don.sql
index 40ab90eab8078c05150e21e6c8e98aae5ef14caa..259cac22966b2315612fe718410eaa68dfce0282 100644
--- a/htdocs/install/mysql/tables/llx_don.sql
+++ b/htdocs/install/mysql/tables/llx_don.sql
@@ -44,7 +44,7 @@ create table llx_don
   fk_don_projet   integer NULL,                  -- projet auquel est fait le don
   fk_user_author  integer NOT NULL,
   fk_user_valid   integer NULL,
-  note            text,
+  note_private    text,
   note_public     text,
   model_pdf       varchar(255),
   import_key      varchar(14)
diff --git a/htdocs/install/mysql/tables/llx_expedition.sql b/htdocs/install/mysql/tables/llx_expedition.sql
index ef30ce38f7af3ac593f57ca455a6d22b1324fa71..6e7bccf08e3fd2aff85c49d78258a8501b5fda88 100644
--- a/htdocs/install/mysql/tables/llx_expedition.sql
+++ b/htdocs/install/mysql/tables/llx_expedition.sql
@@ -48,7 +48,8 @@ create table llx_expedition
   size                  integer,						-- depth
   weight_units          integer,						-- unit of weight
   weight                integer,						-- weight
-  note                  text,
+  note_private          text,
+  note_public           text,
   model_pdf             varchar(255)
   
 )ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_facture.sql b/htdocs/install/mysql/tables/llx_facture.sql
index a9046b49065793f030686207eaf9bd649853dffb..62ea8936e905a3998d0451749eec7e5a86e6d190 100644
--- a/htdocs/install/mysql/tables/llx_facture.sql
+++ b/htdocs/install/mysql/tables/llx_facture.sql
@@ -68,7 +68,7 @@ create table llx_facture
   fk_mode_reglement		integer,								-- mode de reglement (Virement, Prelevement)
   date_lim_reglement	date,									-- date limite de reglement
 
-  note					text,
+  note_private			text,
   note_public			text,
   model_pdf				varchar(255),
   import_key			varchar(14),
diff --git a/htdocs/install/mysql/tables/llx_facture_fourn.sql b/htdocs/install/mysql/tables/llx_facture_fourn.sql
index 372004c44772c1f1c82fb41776ac9a8e710585ef..c2d26a9c7cb00152688ecb5a051600c970e0332b 100644
--- a/htdocs/install/mysql/tables/llx_facture_fourn.sql
+++ b/htdocs/install/mysql/tables/llx_facture_fourn.sql
@@ -61,7 +61,7 @@ create table llx_facture_fourn
   fk_cond_reglement		integer  DEFAULT 1 NOT NULL,   -- condition de reglement (30 jours, fin de mois ...)
   date_lim_reglement 	date,                          -- date limite de reglement
 
-  note					text,
+  note_private			text,
   note_public			text,
   model_pdf				varchar(255),
   import_key			varchar(14),
diff --git a/htdocs/install/mysql/tables/llx_facture_rec.sql b/htdocs/install/mysql/tables/llx_facture_rec.sql
index 8283de388dc70cc51a5a1f914a6e3c9bf299fbaf..0a935a3623d02a4becda4c22b665d7f485346735 100644
--- a/htdocs/install/mysql/tables/llx_facture_rec.sql
+++ b/htdocs/install/mysql/tables/llx_facture_rec.sql
@@ -43,7 +43,7 @@ create table llx_facture_rec
   fk_mode_reglement  integer DEFAULT 0,  -- mode de reglement (Virement, Prelevement)
   date_lim_reglement date,               -- date limite de reglement
 
-  note               text,
+  note_private       text,
   note_public        text,
 
   usenewprice        integer,
diff --git a/htdocs/install/mysql/tables/llx_holiday.sql b/htdocs/install/mysql/tables/llx_holiday.sql
index c83590c84c744d39558c0c78045d157b9115c7df..582b00034ffb19c297a7fd93c3449059f627c8b0 100644
--- a/htdocs/install/mysql/tables/llx_holiday.sql
+++ b/htdocs/install/mysql/tables/llx_holiday.sql
@@ -34,7 +34,7 @@ fk_user_refuse integer DEFAULT NULL,
 date_cancel    DATETIME DEFAULT NULL,
 fk_user_cancel integer DEFAULT NULL,
 detail_refuse  varchar( 250 ) DEFAULT NULL,
-note           text,
+note_private   text,
 note_public    text
 ) 
-ENGINE=innodb;
\ No newline at end of file
+ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_livraison.sql b/htdocs/install/mysql/tables/llx_livraison.sql
index 780e2f5063375c09530790ba5c8fe7f46a8f3cdb..a940e19119970652d619ec2a5b48a66b53ee0854 100644
--- a/htdocs/install/mysql/tables/llx_livraison.sql
+++ b/htdocs/install/mysql/tables/llx_livraison.sql
@@ -37,7 +37,7 @@ create table llx_livraison
   fk_address  			integer,						-- delivery address (deprecated)
   fk_statut             smallint     DEFAULT 0,
   total_ht              double(24,8) DEFAULT 0,
-  note                  text,
+  note_private          text,
   note_public           text,
   model_pdf             varchar(255)
   
diff --git a/htdocs/install/mysql/tables/llx_printer_ipp.sql b/htdocs/install/mysql/tables/llx_printer_ipp.sql
index cb898432fe59cb920e7fb72e8de30ae6f3fba385..19aa1c4d127f09b9284ee6935d281c7c97ef6a2f 100644
--- a/htdocs/install/mysql/tables/llx_printer_ipp.sql
+++ b/htdocs/install/mysql/tables/llx_printer_ipp.sql
@@ -18,7 +18,7 @@
 
 CREATE TABLE llx_printer_ipp 
 (
- rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
+ rowid integer AUTO_INCREMENT PRIMARY KEY,
  tms 	timestamp,
  datec 	datetime,
  printer_name text NOT NULL, 
diff --git a/htdocs/install/mysql/tables/llx_propal.sql b/htdocs/install/mysql/tables/llx_propal.sql
index 2964e768e47fdc66a483b7b75ba0729354687909..3155eed637064589594a6df8b9ccfd379cfba02c 100644
--- a/htdocs/install/mysql/tables/llx_propal.sql
+++ b/htdocs/install/mysql/tables/llx_propal.sql
@@ -57,7 +57,7 @@ create table llx_propal
   fk_cond_reglement		integer,						-- condition de reglement (30 jours, fin de mois ...)
   fk_mode_reglement		integer,						-- mode de reglement (Virement, Prelevement)
  
-  note					text,
+  note_private			text,
   note_public			text,
   model_pdf				varchar(255),
   date_livraison		date DEFAULT NULL,				-- delivery date
diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql
index b0d601fff47af534991f6c7910e6900d4e67f45f..95ceadec503f3d6ee31367e305b52e5e73456b2b 100644
--- a/htdocs/install/mysql/tables/llx_societe.sql
+++ b/htdocs/install/mysql/tables/llx_societe.sql
@@ -62,7 +62,7 @@ create table llx_societe
   tva_intra                varchar(20),                         		-- tva
   capital                  real,                                		-- capital de la societe
   fk_stcomm                integer        DEFAULT 0 NOT NULL,      		-- commercial statut
-  note                     text,                                		--
+  note_private             text,                                		--
   note_public              text,                                        --
   prefix_comm              varchar(5),                          		-- prefix commercial
   client                   tinyint        DEFAULT 0,            		-- client 0/1/2
diff --git a/htdocs/install/mysql/tables/llx_socpeople.sql b/htdocs/install/mysql/tables/llx_socpeople.sql
index 921580394a82279af6dddaa35f9674984728e097..d06e91e53951b60d03914c8b8a844a38ae61c0c6 100644
--- a/htdocs/install/mysql/tables/llx_socpeople.sql
+++ b/htdocs/install/mysql/tables/llx_socpeople.sql
@@ -46,7 +46,7 @@ create table llx_socpeople
   priv				smallint NOT NULL DEFAULT 0,
   fk_user_creat		integer DEFAULT 0,							-- user qui a creel'enregistrement
   fk_user_modif		integer,
-  note				text,
+  note_private		text,
   note_public		text,
   default_lang		varchar(6),
   canvas			varchar(32),			-- type of canvas if used (null by default)
diff --git a/htdocs/install/mysql/tables/llx_user.sql b/htdocs/install/mysql/tables/llx_user.sql
index 6f1f44f6b2cce0e05ec03434972325f175e16071..6042b0906ce758f1c0835050474bb13535d37a93 100644
--- a/htdocs/install/mysql/tables/llx_user.sql
+++ b/htdocs/install/mysql/tables/llx_user.sql
@@ -1,6 +1,6 @@
 -- ============================================================================
 -- Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
--- Copyright (C) 2006-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
+-- Copyright (C) 2006-2013 Laurent Destailleur  <eldy@users.sourceforge.net>
 -- Copyright (C) 2007-2013 Regis Houssin        <regis.houssin@capnetworks.com>
 --
 -- This program is free software; you can redistribute it and/or modify
@@ -47,9 +47,6 @@ create table llx_user
   email             varchar(255),
   signature         text DEFAULT NULL,
   admin             smallint DEFAULT 0,
-  webcal_login      varchar(25),			-- TODO move to an extra table (ex: llx_extra_fields)
-  phenix_login      varchar(25),			-- TODO move to an extra table (ex: llx_extra_fields)
-  phenix_pass       varchar(128),			-- TODO move to an extra table (ex: llx_extra_fields)
   module_comm       smallint DEFAULT 1,
   module_compta     smallint DEFAULT 1,
   fk_societe        integer,
@@ -64,6 +61,6 @@ create table llx_user
   openid            varchar(255),
   statut            tinyint DEFAULT 1,
   photo             varchar(255),     -- filename or url of photo
-  lang              varchar(6)
-  
+  lang              varchar(6),
+  color				varchar(6)
 )ENGINE=innodb;
diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang
index f143a7fa1675d6281225e734d7eb1187047edfd0..f52dea49651fab2063ca7c92a03bea445d6feaee 100644
--- a/htdocs/langs/en_US/mails.lang
+++ b/htdocs/langs/en_US/mails.lang
@@ -82,16 +82,16 @@ ActivateCheckReadKey=Key use to encrypt URL use for "Read Receipt" and "Unsubcri
 EMailSentToNRecipients=EMail sent to %s recipients.
 
 # Libelle des modules de liste de destinataires mailing
-MailingModuleDescContactCompanies=Contacts of all third parties (customer, prospect, supplier, ...)
+MailingModuleDescContactCompanies=Contacts/addresses of all third parties (customer, prospect, supplier, ...)
 MailingModuleDescDolibarrUsers=Dolibarr users
 MailingModuleDescFundationMembers=Foundation members with emails
 MailingModuleDescEmailsFromFile=EMails from a text file (email;lastname;firstname;other)
 MailingModuleDescEmailsFromUser=EMails from user input (email;lastname;firstname;other)
 MailingModuleDescContactsCategories=Third parties (by category)
 MailingModuleDescDolibarrContractsLinesExpired=Third parties with expired contract's lines
-MailingModuleDescContactsByCompanyCategory=Contacts of third parties (by third parties category)
+MailingModuleDescContactsByCompanyCategory=Contacts/addresses of third parties (by third parties category)
 MailingModuleDescMembersCategories=Foundation members (by categories)
-MailingModuleDescContactsByFunction=Contacts of third parties (by position/function)
+MailingModuleDescContactsByFunction=Contacts/addresses of third parties (by position/function)
 
 
 LineInFile=Line %s in file
@@ -100,7 +100,7 @@ MailSelectedRecipients=Selected recipients
 MailingArea=EMailings area
 LastMailings=Last %s emailings
 TargetsStatistics=Targets statistics
-NbOfCompaniesContacts=Unique contacts of companies
+NbOfCompaniesContacts=Unique contacts/addresses
 MailNoChangePossible=Recipients for validated emailing can't be changed
 SearchAMailing=Search mailing
 SendMailing=Send emailing
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index 70dc7fe2555ae8c4e3257b35150e13aafa72c63b..0d1a2aaf5e00cc62b9fcba934017c2ae7b090a35 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -953,7 +953,8 @@ ExtraFieldsContacts=Attributs supplémentaires (contacts/adresses)
 ExtraFieldsMember=Attributs supplémentaires (adhérents)
 ExtraFieldsMemberType=Attributs supplémentaires (type d'adhérents)
 ExtraFieldsCustomerInvoices=Attributs supplémentaires (factures clients)
-ExtraFieldsSupplierOrders=Attributs supplémentaires (commandes fournisseurs)
+ExtraFieldsSupplierOrders=Attributs supplémentaires (commandes)
+ExtraFieldsSupplierInvoices=Attributs supplémentaires (factures)
 ExtraFieldHasWrongValue=L'attribut %s a une valeur incorrecte.
 AlphaNumOnlyCharsAndNoSpace=uniquement caractères alphanumériques sans espace
 SendingMailSetup=Configuration de l'envoi par mail
diff --git a/htdocs/langs/fr_FR/mails.lang b/htdocs/langs/fr_FR/mails.lang
index be08ccad7e825f1fe7d6bcdc5d1fab15d9f6e484..a94aa8ff14973dafe5282f4a45bc6d39e303e8ac 100644
--- a/htdocs/langs/fr_FR/mails.lang
+++ b/htdocs/langs/fr_FR/mails.lang
@@ -99,7 +99,7 @@ MailSelectedRecipients=Destinataires sélectionnés
 MailingArea=Espace emailings
 LastMailings=Les %s derniers emailings
 TargetsStatistics=Statistiques destinataires
-NbOfCompaniesContacts=Contacts uniques des sociétés
+NbOfCompaniesContacts=Contacts/adresses uniques
 MailNoChangePossible=Destinataires d'un mailing validé non modifiables
 SearchAMailing=Rechercher un mailing
 SendMailing=Envoi emailing
diff --git a/htdocs/langs/fr_FR/suppliers.lang b/htdocs/langs/fr_FR/suppliers.lang
index 932615ff1813b129accc74c92bf59cfd3d39de65..dbe2edbe4abb725476de43549e381a7c8f16f908 100644
--- a/htdocs/langs/fr_FR/suppliers.lang
+++ b/htdocs/langs/fr_FR/suppliers.lang
@@ -5,6 +5,7 @@ Supplier=Fournisseur
 AddSupplier=Ajouter un fournisseur
 SupplierRemoved=Fournisseur supprimé
 SuppliersInvoice=Facture fournisseur
+SuppliersInvoices=Factures fournisseur
 NewSupplier=Nouveau fournisseur
 History=Historique
 ListOfSuppliers=Liste des fournisseurs
diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php
index d5dce8c68308971104f3860ad8bcd113a4ccd0cc..ea1962be34c8095647444e5821613bc711f67e47 100644
--- a/htdocs/livraison/class/livraison.class.php
+++ b/htdocs/livraison/class/livraison.class.php
@@ -4,6 +4,7 @@
  * Copyright (C) 2006-2007 Laurent Destailleur   <eldy@users.sourceforge.net>
  * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  * Copyright (C) 2011-2012 Philippe Grand	     <philippe.grand@atoo-net.com>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -49,6 +50,9 @@ class Livraison extends CommonObject
 	var $socid;
 	var $ref_customer;
 	var $statut;
+	
+	var $note_public;
+	var $note_private;
 
 	var $expedition_id;
 
@@ -106,15 +110,19 @@ class Livraison extends CommonObject
 		$sql.= ", fk_user_author";
 		$sql.= ", date_delivery";
 		$sql.= ", fk_address";
+		$sql.= ", note_private";
+		$sql.= ", note_public";
 		$sql.= ") VALUES (";
 		$sql.= "'(PROV)'";
 		$sql.= ", ".$conf->entity;
 		$sql.= ", ".$this->socid;
-		$sql.= ", '".$this->ref_customer."'";
+		$sql.= ", '".$this->db->escape($this->ref_customer)."'";
 		$sql.= ", ".$this->db->idate($now);
 		$sql.= ", ".$user->id;
 		$sql.= ", ".($this->date_delivery?"'".$this->db->idate($this->date_delivery)."'":"null");
 		$sql.= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : "null");
+		$sql.= ", ".(!empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
+		$sql.= ", ".(!empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
 		$sql.= ")";
 
 		dol_syslog("Livraison::create sql=".$sql, LOG_DEBUG);
@@ -253,7 +261,7 @@ class Livraison extends CommonObject
 		global $conf;
 
 		$sql = "SELECT l.rowid, l.fk_soc, l.date_creation, l.date_valid, l.ref, l.ref_customer, l.fk_user_author,";
-		$sql.=" l.total_ht, l.fk_statut, l.fk_user_valid, l.note, l.note_public";
+		$sql.=" l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
 		$sql.= ", l.date_delivery, l.fk_address, l.model_pdf";
 		$sql.= ", el.fk_source as origin_id, el.sourcetype as origin";
 		$sql.= " FROM ".MAIN_DB_PREFIX."livraison as l";
@@ -279,7 +287,8 @@ class Livraison extends CommonObject
 				$this->user_author_id       = $obj->fk_user_author;
 				$this->user_valid_id        = $obj->fk_user_valid;
 				$this->fk_delivery_address  = $obj->fk_address;
-				$this->note                 = $obj->note;
+				$this->note                 = $obj->note_private; //TODO deprecated
+				$this->note_private         = $obj->note_private;
 				$this->note_public          = $obj->note_public;
 				$this->modelpdf             = $obj->model_pdf;
 				$this->origin               = $obj->origin;		// May be 'shipping'
@@ -488,7 +497,8 @@ class Livraison extends CommonObject
 
 		$this->origin               = $expedition->element;
 		$this->origin_id            = $expedition->id;
-		$this->note                 = $expedition->note;
+		$this->note_private         = $expedition->note_private;
+		$this->note_public          = $expedition->note_public;
 		$this->fk_project           = $expedition->fk_project;
 		$this->date_delivery        = $expedition->date_delivery;
 		$this->fk_delivery_address  = $expedition->fk_delivery_address;
@@ -792,7 +802,8 @@ class Livraison extends CommonObject
 		$this->specimen=1;
 		$this->socid = 1;
 		$this->date_delivery = $now;
-		$this->note_public='SPECIMEN';
+		$this->note_public='Pulbic note';
+		$this->note_private='Private note';
 
 		$i=0;
 		$line=new LivraisonLigne($this->db);
diff --git a/htdocs/livraison/fiche.php b/htdocs/livraison/fiche.php
index b3ae95fd51276a896f4ca19e596616a24ae36454..2849daa9c675023eba2c52c08fc5030257216e8e 100644
--- a/htdocs/livraison/fiche.php
+++ b/htdocs/livraison/fiche.php
@@ -4,6 +4,7 @@
  * Copyright (C) 2005		Simon TOSSER			<simon@kornog-computing.com>
  * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2007		Franky Van Liedekerke	<franky.van.liedekerke@telenet.be>
+ * Copyright (C) 2013       Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -446,7 +447,7 @@ else
 		$delivery = new Livraison($db);
 		$result = $delivery->fetch($id);
 		$delivery->fetch_thirdparty();
-
+		
 		$expedition=new Expedition($db);
 		$result = $expedition->fetch($delivery->origin_id);
 		$typeobject = $expedition->origin;
@@ -537,6 +538,23 @@ else
 			print '<tr><td>'.$langs->trans("DateReceived").'</td>';
 			print '<td colspan="3">'.dol_print_date($delivery->date_delivery,'daytext')."</td>\n";
 			print '</tr>';
+			
+			// Note Public  
+            print '<tr><td>'.$langs->trans("NotePublic").'</td>';
+            print '<td colspan="3">';
+            print nl2br($delivery->note_public);
+            /*$doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);*/
+            print "</td></tr>";
+			
+			// Note Private
+            print '<tr><td>'.$langs->trans("NotePrivate").'</td>';
+            print '<td colspan="3">';
+            print nl2br($delivery->note_private);
+            /*$doleditor = new DolEditor('note_pprivate', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
+            print $doleditor->Create(1);*/
+            print "</td></tr>";
+            
 
 			// Statut
 			print '<tr><td>'.$langs->trans("Status").'</td>';
diff --git a/htdocs/opensurvey/admin/index.php b/htdocs/opensurvey/admin/index.php
new file mode 100755
index 0000000000000000000000000000000000000000..02c6a5ea12509a8b97969c7f169f217b6ef9c74a
--- /dev/null
+++ b/htdocs/opensurvey/admin/index.php
@@ -0,0 +1,62 @@
+<?php
+/* Copyright (C) 2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/admin/index.php
+ *	\ingroup    opensurvey
+ *	\brief      Setup page of opensurvey
+ */
+
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+// Security check
+if (!$user->admin) accessforbidden();
+
+
+
+
+/*
+ * View
+ */
+
+$langs->load("opensurvey@opensurvey");
+llxHeader();
+
+print_fiche_titre($langs->trans("OpenSurveyArea"));
+
+echo $langs->trans("OpenSurveyNothingToSetup").'<br><br>'."\n";
+
+// Link
+print img_picto('','object_globe.png').' '.$langs->trans("PublicLinkToCreateSurvey").':<br>';
+
+// Define $urlwithroot
+$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/index.php',1);
+$urllink='<a href="'.$url.'" target="_blank">'.$url.'</a>';
+print $urllink;
+
+
+llxFooter();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/adminstuds.php b/htdocs/opensurvey/adminstuds.php
new file mode 100755
index 0000000000000000000000000000000000000000..d3547a4ac518e385f29b90915b5e14e0c5b02842
--- /dev/null
+++ b/htdocs/opensurvey/adminstuds.php
@@ -0,0 +1,352 @@
+<?php
+/* Copyright (C) 2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/adminstuds.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to edit survey
+ */
+
+require_once('../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+
+// Security check
+if (!$user->admin) accessforbidden();
+
+
+// Initialisation des variables
+$action=GETPOST('action');
+$numsondage = $numsondageadmin = '';
+if (GETPOST('sondage'))
+{
+	if (strlen(GETPOST('sondage')) == 24)	// recuperation du numero de sondage admin (24 car.) dans l'URL
+	{
+		$numsondageadmin=GETPOST("sondage",'alpha');
+		$numsondage=substr($numsondageadmin, 0, 16);
+	}
+	else
+	{
+		$numsondageadmin='';
+		$numsondage=GETPOST("sondage",'alpha');
+	}
+}
+
+$object=new Opensurveysondage($db);
+
+$expiredate=dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), GETPOST('expireyear'));
+
+
+
+/*
+ * Actions
+ */
+
+
+// Delete
+if ($action == 'delete_confirm')
+{
+	$result=$object->delete($user,'',$numsondageadmin);
+
+	header('Location: '.dol_buildpath('/opensurvey/list.php',1));
+	exit();
+}
+
+// Update
+if ($action == 'update')
+{
+	$error=0;
+
+	if (! GETPOST('nouveautitre'))
+	{
+		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Title")),'errors');
+		$error++;
+		$action = 'edit';
+	}
+
+	if (! $error)
+	{
+		$res=$object->fetch(0,$numsondageadmin);
+		if ($res < 0) dol_print_error($db,$object->error);
+	}
+
+	if (! $error)
+	{
+		$object->titre = GETPOST('nouveautitre');
+		$object->commentaires = GETPOST('nouveauxcommentaires');
+		$object->mail_admin = GETPOST('nouvelleadresse');
+		$object->date_fin = $expiredate;
+		$object->survey_link_visible = GETPOST('survey_link_visible')=='on'?1:0;
+		$object->canedit = GETPOST('canedit')=='on'?1:0;
+
+		$res=$object->update($user);
+		if ($res < 0)
+		{
+			setEventMessage($object->error,'errors');
+			$action='edit';
+		}
+	}
+}
+
+
+// Add comment
+if (GETPOST('ajoutcomment'))
+{
+	$error=0;
+
+	if (! GETPOST('comment'))
+	{
+		$error++;
+		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Comment")),'errors');
+	}
+	if (! GETPOST('commentuser'))
+	{
+		$error++;
+		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("User")),'errors');
+	}
+
+	if (! $error)
+	{
+		$comment = GETPOST("comment");
+		$comment_user = GETPOST('commentuser');
+
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)";
+		$sql.= " VALUES ('".$db->escape($numsondage)."','".$db->escape($comment)."','".$db->escape($comment_user)."')";
+		$resql = $db->query($sql);
+		dol_syslog("sql=".$sql);
+		if (! $resql)
+		{
+			$err |= COMMENT_INSERT_FAILED;
+		}
+	}
+}
+
+// Delete comment
+$idcomment=GETPOST('deletecomment','int');
+if ($idcomment)
+{
+	$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$idcomment;
+	$resql = $db->query($sql);
+}
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+
+$result=$object->fetch(0,$numsondage);
+if ($result <= 0)
+{
+	print $langs->trans("ErrorRecordNotFound");
+	llxFooter();
+	exit;
+}
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeader('',$object->titre, 0, 0, 0, 0, $arrayofjs, $arrayofcss);
+
+
+// Define format of choices
+$toutsujet=explode(",",$object->sujet);
+$listofanswers=array();
+foreach ($toutsujet as $value)
+{
+	$tmp=explode('@',$value);
+	$listofanswers[]=array('label'=>$tmp[0],'format'=>($tmp[1]?$tmp[1]:'checkbox'));
+}
+$toutsujet=str_replace("@","<br>",$toutsujet);
+$toutsujet=str_replace("°","'",$toutsujet);
+
+
+print '<form name="updatesurvey" action="'.$_SERVER["PHP_SELF"].'?sondage='.$numsondageadmin.'" method="POST">'."\n";
+print '<input type="hidden" name="action" value="update">';
+
+$head = array();
+
+$head[0][0] = '';
+$head[0][1] = $langs->trans("Card");
+$head[0][2] = 'general';
+$h++;
+
+$head[1][0] = 'adminstuds_preview.php?sondage='.$object->id_sondage_admin;
+$head[1][1] = $langs->trans("SurveyResults").'/'.$langs->trans("Preview");
+$head[1][2] = 'preview';
+$h++;
+
+print dol_get_fiche_head($head,'general',$langs->trans("Survey"),0,dol_buildpath('/opensurvey/img/object_opensurvey.png',1),1);
+
+
+print '<table class="border" width="100%">';
+
+$linkback = '<a href="'.dol_buildpath('/opensurvey/list.php',1).'">'.$langs->trans("BackToList").'</a>';
+
+// Ref
+print '<tr><td width="18%">'.$langs->trans('Ref').'</td>';
+print '<td colspan="3">';
+print $form->showrefnav($object, 'sondage', $linkback, 1, 'id_sondage_admin', 'id_sondage_admin');
+print '</td>';
+print '</tr>';
+
+// Type
+$type=($object->format=="A"||$object->format=="A+")?'classic':'date';
+print '<tr><td>'.$langs->trans("Type").'</td><td colspan="2">';
+print img_picto('',dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'),1),'width="16"',1);
+print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'</td></tr>';
+
+// Title
+print '<tr><td>';
+$adresseadmin=$object->mail_admin;
+print $langs->trans("Title") .'</td><td colspan="2">';
+if ($action == 'edit')
+{
+	print '<input type="text" name="nouveautitre" size="40" value="'.dol_escape_htmltag($object->titre).'">';
+}
+else print $object->titre;
+print '</td></tr>';
+
+// Auteur
+print '<tr><td>';
+print $langs->trans("Author") .'</td><td colspan="2">';
+print $object->nom_admin;
+print '</td></tr>';
+
+// Description
+print '<tr><td>'.$langs->trans("Description") .'</td><td colspan="2">';
+if ($action == 'edit')
+{
+	print '<textarea name="nouveauxcommentaires" rows="7" cols="80">'.$object->commentaires.'</textarea>'."\n";
+}
+else print dol_nl2br($object->commentaires);
+print '</td></tr>';
+
+// EMail
+print '<tr><td>'.$langs->trans("EMail") .'</td><td colspan="2">';
+if ($action == 'edit')
+{
+	print '<input type="text" name="nouvelleadresse" size="40" value="'.$object->mail_admin.'">';
+}
+else print dol_print_email($object->mail_admin);
+print '</td></tr>';
+
+// Can edit other votes
+print '<tr><td>'.$langs->trans('CanEditVotes').'</td><td colspan="2">';
+if ($action == 'edit')
+{
+	print '<input type="checkbox" name="canedit" size="40"'.($object->canedit?' checked="true"':'').'">';
+}
+else print yn($object->canedit);
+print '</td></tr>';
+
+// Expire date
+print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">';
+if ($action == 'edit') print $form->select_date($expiredate?$expiredate:$object->date_fin,'expire');
+else print dol_print_date($object->date_fin,'day');
+print '</td></tr>';
+
+
+// Link
+print '<tr><td>'.img_picto('','object_globe.png').' '.$langs->trans("UrlForSurvey",'').'</td><td colspan="2">';
+
+// Define $urlwithroot
+$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/studs.php',1).'?sondage='.$numsondage;
+$urllink='<a href="'.$url.'" target="_blank">'.$url.'</a>';
+print $urllink;
+
+print '</table>';
+
+if ($action == 'edit') print '<center><br><input type="submit" class="button" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'"></center>';
+
+print '</form>'."\n";
+
+dol_fiche_end();
+
+
+/*
+ * Barre d'actions
+ */
+print '<div class="tabsAction">';
+
+if ($action != 'edit') print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&sondage=' . $numsondageadmin . '">'.$langs->trans("Modify") . '</a>';
+
+if ($action != 'edit') print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?suppressionsondage=1&sondage='.$numsondageadmin.'&amp;action=delete">'.$langs->trans('Delete').'</a>';
+
+print '</div>';
+
+if ($action == 'delete')
+{
+	print $form->formconfirm($_SERVER["PHP_SELF"].'?&sondage='.$numsondageadmin, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll",$id), 'delete_confirm', '', '', 1);
+}
+
+
+
+print '<br>';
+
+
+print '<form name="formulaire5" action="#" method="POST">'."\n";
+
+print_fiche_titre($langs->trans("CommentsOfVoters"),'','');
+
+// Comment list
+$sql = 'SELECT id_comment, usercomment, comment';
+$sql.= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments';
+$sql.= " WHERE id_sondage='".$db->escape($numsondage)."'";
+$sql.= " ORDER BY id_comment";
+$resql = $db->query($sql);
+$num_rows=$db->num_rows($resql);
+if ($num_rows > 0)
+{
+	$i = 0;
+	while ( $i < $num_rows)
+	{
+		$obj=$db->fetch_object($resql);
+		print '<a href="'.dol_buildpath('/opensurvey/adminstuds.php',1).'?deletecomment='.$obj->id_comment.'&sondage='.$numsondageadmin.'"> '.img_picto('', 'delete.png').'</a> ';
+		print $obj->usercomment.' : '.dol_nl2br($obj->comment)." <br>";
+		$i++;
+	}
+}
+else
+{
+	print $langs->trans("NoCommentYet").'<br>';;
+}
+
+print '<br>';
+
+// Add comment
+print $langs->trans("AddACommentForPoll") . '<br>';
+print '<textarea name="comment" rows="2" cols="80"></textarea><br>'."\n";
+print $langs->trans("Name") .' : <input type=text name="commentuser"><br>'."\n";
+print '<input type="submit" class="button" name="ajoutcomment" value="'.dol_escape_htmltag($langs->trans("AddComment")).'"><br>'."\n";
+if (isset($erreur_commentaire_vide) && $erreur_commentaire_vide=="yes") {
+	print "<font color=#FF0000>" . $langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Name")) . "</font>";
+}
+
+print '</form>';
+
+llxFooterSurvey();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/adminstuds_preview.php b/htdocs/opensurvey/adminstuds_preview.php
new file mode 100755
index 0000000000000000000000000000000000000000..4d07cc67ba374834723a4ef27d2e6043809010f6
--- /dev/null
+++ b/htdocs/opensurvey/adminstuds_preview.php
@@ -0,0 +1,1064 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/admin_studs_preview.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to preview votes of a survey
+ */
+
+$res=0;
+require_once('../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+
+// Security check
+if (!$user->admin) accessforbidden();
+
+
+// Init vars
+$action=GETPOST('action');
+$numsondageadmin=GETPOST("sondage");
+$numsondage=substr($numsondageadmin, 0, 16);
+
+$object=new Opensurveysondage($db);
+$object->fetch(0,$numsondageadmin);
+$nblignes=count($object->fetch_lines());
+
+
+/*
+ * Actions
+ */
+
+$nbcolonnes = substr_count($object->sujet, ',') + 1;
+
+// Add vote
+if (isset($_POST["boutonp"]) || isset($_POST["boutonp_x"]))
+{
+	if (GETPOST('nom'))
+	{
+		$erreur_prenom = false;
+
+		$nouveauchoix = '';
+		for ($i=0;$i<$nbcolonnes;$i++)
+		{
+			if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
+			{
+				$nouveauchoix.="1";
+			}
+			else if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2')
+			{
+				$nouveauchoix.="2";
+			}
+			else { // sinon c'est 0
+				$nouveauchoix.="0";
+			}
+		}
+
+		$nom=substr(GETPOST("nom"),0,64);
+
+		// Check if vote already exists
+		$sql = 'SELECT id_users, nom';
+		$sql.= ' FROM '.MAIN_DB_PREFIX."opensurvey_user_studs';
+		$sql.= ' WHERE id_sondage='".$db->escape($numsondage)."' AND nom = '".$db->escape($nom)."'";
+		$sql.= ' ORDER BY id_users';
+		$resql = $db->query($sql);
+		$num_rows = $db->num_rows($resql);
+		if ($num_rows > 0)
+		{
+			setEventMessage($langs->trans("VoteNameAlreadyExists"),'errors');
+			$error++;
+		}
+		else
+		{
+			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)';
+			$sql.= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')";
+			$resql=$db->query($sql);
+			if (! $resql) dol_print_error($db);
+		}
+	}
+}
+
+// Update vote
+$testmodifier = false;
+$testligneamodifier = false;
+$ligneamodifier = -1;
+for ($i=0; $i<$nblignes; $i++)
+{
+	if (isset($_POST['modifierligne'.$i]))
+	{
+		$ligneamodifier=$i;
+		$testligneamodifier=true;
+	}
+
+	//test pour voir si une ligne est a modifier
+	if (isset($_POST['validermodifier'.$i]))
+	{
+		$modifier=$i;
+		$testmodifier=true;
+	}
+}
+if ($testmodifier)
+{
+	//var_dump($_POST);exit;
+	$nouveauchoix = '';
+	for ($i = 0; $i < $nbcolonnes; $i++)
+	{
+		//var_dump($_POST["choix$i"]);
+		if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
+		{
+			$nouveauchoix.="1";
+		}
+		else if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2')
+		{
+			$nouveauchoix.="2";
+		}
+		else { // sinon c'est 0
+			$nouveauchoix.="0";
+		}
+	}
+
+	$idtomodify=$_POST["idtomodify".$modifier];
+	$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_user_studs";
+	$sql.= " SET reponses = '".$db->escape($nouveauchoix)."'";
+	$sql.= " WHERE id_users = '".$db->escape($idtomodify)."'";
+
+	dol_syslog("sql=".$sql);
+	$resql = $db->query($sql);
+	if (! $resql) dol_print_error($db);
+}
+
+// Add column (not for date)
+if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && ($object->format == "A" || $object->format == "A+"))
+{
+	$nouveauxsujets=$object->sujet;
+
+	//on rajoute la valeur a la fin de tous les sujets deja entrés
+	$nouveauxsujets.=',';
+	$nouveauxsujets.=str_replace(array(",","@"), " ", $_POST["nouvellecolonne"]).(empty($_POST["typecolonne"])?'':'@'.$_POST["typecolonne"]);
+
+	//mise a jour avec les nouveaux sujets dans la base
+	$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
+	$sql.= " SET sujet = '".$db->escape($nouveauxsujets)."'";
+	$sql.= " WHERE id_sondage = '".$db->escape($numsondage)."'";
+	dol_syslog("sql=".$sql);
+	$resql = $db->query($sql);
+	if (! $resql) dol_print_error($db);
+}
+
+// Add column (with format date)
+if (isset($_POST["ajoutercolonne"]) && ($object->format == "D" || $object->format == "D+"))
+{
+	$nouveauxsujets=$object->sujet;
+
+	if (isset($_POST["nouveaujour"]) && $_POST["nouveaujour"] != "vide" &&
+		isset($_POST["nouveaumois"]) && $_POST["nouveaumois"] != "vide" &&
+		isset($_POST["nouvelleannee"]) && $_POST["nouvelleannee"] != "vide") {
+
+		$nouvelledate=dol_mktime(0, 0, 0, $_POST["nouveaumois"], $_POST["nouveaujour"], $_POST["nouvelleannee"]);
+
+		if (isset($_POST["nouvelleheuredebut"]) && $_POST["nouvelleheuredebut"]!="vide"){
+			$nouvelledate.="@";
+			$nouvelledate.=$_POST["nouvelleheuredebut"];
+			$nouvelledate.="h";
+
+			if ($_POST["nouvelleminutedebut"]!="vide") {
+				$nouvelledate.=$_POST["nouvelleminutedebut"];
+			}
+		}
+
+		if (isset($_POST["nouvelleheurefin"]) && $_POST["nouvelleheurefin"]!="vide"){
+			$nouvelledate.="-";
+			$nouvelledate.=$_POST["nouvelleheurefin"];
+			$nouvelledate.="h";
+
+			if ($_POST["nouvelleminutefin"]!="vide") {
+				$nouvelledate.=$_POST["nouvelleminutefin"];
+			}
+		}
+
+		if($_POST["nouvelleheuredebut"] == "vide" || (isset($_POST["nouvelleheuredebut"]) && isset($_POST["nouvelleheurefin"]) && (($_POST["nouvelleheuredebut"] < $_POST["nouvelleheurefin"]) || (($_POST["nouvelleheuredebut"] == $_POST["nouvelleheurefin"]) && ($_POST["nouvelleminutedebut"] < $_POST["nouvelleminutefin"]))))) {
+			$erreur_ajout_date = false;
+		} else {
+			$erreur_ajout_date = "yes";
+		}
+
+		//on rajoute la valeur dans les valeurs
+		$datesbase = explode(",",$object->sujet);
+		$taillebase = count($datesbase);
+
+		//recherche de l'endroit de l'insertion de la nouvelle date dans les dates deja entrées dans le tableau
+		if ($nouvelledate < $datesbase[0]) {
+			$cleinsertion = 0;
+		} elseif ($nouvelledate > $datesbase[$taillebase-1]) {
+			$cleinsertion = count($datesbase);
+		} else {
+			$nbdatesbase=count($datesbase);
+			for ($i = 0; $i < $nbdatesbase; $i++) 
+			{
+				$j = $i + 1;
+				if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) {
+					$cleinsertion = $j;
+				}
+			}
+		}
+
+		array_splice($datesbase, $cleinsertion, 0, $nouvelledate);
+		$cle = array_search($nouvelledate, $datesbase);
+		$dateinsertion = '';
+		for ($i = 0; $i < count($datesbase); $i++) {
+			$dateinsertion.=",";
+			$dateinsertion.=$datesbase[$i];
+		}
+
+		$dateinsertion = substr("$dateinsertion", 1);
+
+		//mise a jour avec les nouveaux sujets dans la base
+		if (isset($erreur_ajout_date) && !$erreur_ajout_date)
+		{
+			$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
+			$sql.= " SET sujet = '".$db->escape($dateinsertion)."'";
+			$sql.= " WHERE id_sondage = '".$db->escape($numsondage)."'";
+			dol_syslog("sql=".$sql);
+			$resql = $db->query($sql);
+			if (! $resql) dol_print_error($db);
+
+			if ($nouvelledate > strtotime($object->date_fin))
+			{
+				$date_fin=$nouvelledate+200000;
+				$sql = 'UPDATE '.MAIN_DB_PREFIX.'opensurvey_sondage';
+				$sql.= " SET date_fin = '".$db->escape($date_fin)."'";
+				$sql.= " WHERE id_sondage = '".$db->escape($numsondage)."'";
+				dol_syslog("sql=".$sql);
+				$resql = $db->query($sql);
+				if (! $resql) dol_print_error($db);
+			}
+		}
+
+		$adresseadmin = $object->mail_admin;
+	}
+	else
+	{
+		$erreur_ajout_date="yes";
+	}
+}
+
+// Delete line
+for ($i = 0; $i < $nblignes; $i++)
+{
+	if (isset($_POST["effaceligne$i"]) || isset($_POST['effaceligne'.$i.'_x']))
+	{
+		$compteur=0;
+
+		// Loop on each answer
+		$compteur = 0;
+		$sql ="SELECT id_users, nom, id_sondage, reponses";
+		$sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
+		$sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'";
+		dol_syslog('sql='.$sql);
+		$resql=$db->query($sql);
+		if (! $resql) dol_print_error($db);
+		$num=$db->num_rows($resql);
+		while ($compteur < $num)
+		{
+			$obj=$db->fetch_object($resql);
+
+			if ($compteur==$i)
+			{
+				$sql2 = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs';
+				$sql2.= ' WHERE id_users = '.$db->escape($obj->id_users);
+				$resql2 = $db->query($sql2);
+			}
+
+			$compteur++;
+		}
+	}
+}
+
+// Delete column
+for ($i = 0; $i < $nbcolonnes; $i++)
+{
+	if ((isset($_POST["effacecolonne$i"]) || isset($_POST['effacecolonne'.$i.'_x'])) && $nbcolonnes > 1)
+	{
+		$db->begin();
+
+		$toutsujet = explode(",",$object->sujet);
+		$j = 0;
+		$nouveauxsujets = '';
+
+		//parcours de tous les sujets actuels
+		while (isset($toutsujet[$j]))
+		{
+			//si le sujet n'est pas celui qui a été effacé alors on concatene
+			if ($i != $j)
+			{
+				if (! empty($nouveauxsujets)) $nouveauxsujets .= ',';
+				$nouveauxsujets .= $toutsujet[$j];
+			}
+
+			$j++;
+		}
+
+		// Mise a jour des sujets dans la base
+		$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
+		$sql.= " SET sujet = '".$db->escape($nouveauxsujets)."' WHERE id_sondage = '".$db->escape($numsondage)."'";
+		dol_syslog("sql=".$sql);
+		$resql = $db->query($sql);
+		if (! $resql) dol_print_error($db);
+
+		// Clean current answer to remove deleted columns
+		$compteur = 0;
+		$sql ="SELECT id_users, nom, id_sondage, reponses";
+		$sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
+		$sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'";
+		dol_syslog('sql='.$sql);
+		$resql=$db->query($sql);
+		if (! $resql)
+		{
+			dol_print_error($db);
+			exit;
+		}
+		$num=$db->num_rows($resql);
+		while ($compteur < $num)
+		{
+			$obj=$db->fetch_object($resql);
+
+			$newcar = '';
+			$ensemblereponses = $obj->reponses;
+
+			// parcours de toutes les réponses actuelles
+			for ($j = 0; $j < $nbcolonnes; $j++)
+			{
+				$car=substr($ensemblereponses, $j, 1);
+				//si les reponses ne concerne pas la colonne effacée, on concatene
+				if ($i != $j) {
+					$newcar .= $car;
+				}
+			}
+
+			// mise a jour des reponses utilisateurs dans la base
+			$sql2 = 'UPDATE '.MAIN_DB_PREFIX.'opensurvey_user_studs';
+			$sql2.= " SET reponses = '".$db->escape($newcar)."'";
+			$sql2.= " WHERE id_users = '".$db->escape($obj->id_users)."'";
+			//print $sql2;
+			dol_syslog('sql='.$sql2);
+			$resql2 = $db->query($sql2);
+
+			$compteur++;
+		}
+
+		$db->commit();
+	}
+}
+
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+
+$result=$object->fetch(0,$numsondage);
+if ($result <= 0)
+{
+	print $langs->trans("ErrorRecordNotFound");
+	llxFooter();
+	exit;
+}
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeader('',$object->titre, 0, 0, 0, 0, $arrayofjs, $arrayofcss);
+
+
+// Define format of choices
+$toutsujet=explode(",",$object->sujet);
+$listofanswers=array();
+foreach ($toutsujet as $value)
+{
+	$tmp=explode('@',$value);
+	$listofanswers[]=array('label'=>$tmp[0],'format'=>($tmp[1]?$tmp[1]:'checkbox'));
+}
+$toutsujet=str_replace("@","<br>",$toutsujet);
+$toutsujet=str_replace("°","'",$toutsujet);
+
+
+print '<form name="formulaire4" action="#" method="POST" onkeypress="javascript:process_keypress(event)">'."\n";
+
+$head = array();
+
+$head[0][0] = 'adminstuds.php?sondage='.$object->id_sondage_admin;
+$head[0][1] = $langs->trans("Card");
+$head[0][2] = 'general';
+$h++;
+
+$head[1][0] = 'adminstuds_preview.php?sondage='.$object->id_sondage_admin;
+$head[1][1] = $langs->trans("SurveyResults").'/'.$langs->trans("Preview");
+$head[1][2] = 'preview';
+$h++;
+
+print dol_get_fiche_head($head,'preview',$langs->trans("Survey"),0,dol_buildpath('/opensurvey/img/object_opensurvey.png',1),1);
+
+
+print '<table class="border" width="100%">';
+
+$linkback = '<a href="'.dol_buildpath('/opensurvey/list.php',1).(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+
+// Ref
+print '<tr><td width="18%">'.$langs->trans('Ref').'</td>';
+print '<td colspan="3">';
+print $form->showrefnav($object, 'sondage', $linkback, 1, 'id_sondage_admin', 'id_sondage_admin');
+print '</td>';
+print '</tr>';
+
+// Type
+$type=($object->format=="A"||$object->format=="A+")?'classic':'date';
+print '<tr><td>'.$langs->trans("Type").'</td><td colspan="2">';
+print img_picto('',dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'),1),'width="16"',1);
+print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'</td></tr>';
+
+// Link
+print '<tr><td>'.img_picto('','object_globe.png').' '.$langs->trans("UrlForSurvey",'').'</td><td>';
+
+// Define $urlwithroot
+$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/studs.php',1).'?sondage='.$numsondage;
+$urlvcal='<a href="'.$url.'" target="_blank">'.$url.'</a>';
+print $urlvcal;
+
+
+print '</table>';
+
+dol_fiche_end();
+
+print '</form>'."\n";
+
+print '<div class="tabsAction">';
+
+print '<a class="butAction" href="public/exportcsv.php?sondage=' . $numsondage . '">'.$langs->trans("ExportSpreadsheet") .' (.CSV)' . '</a>';
+
+print '</div>';
+
+
+showlogo();
+
+
+// Add form to add a field
+if (GETPOST('ajoutsujet'))
+{
+	//on recupere les données et les sujets du sondage
+	print '<form name="formulaire" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
+	print '<input type="hidden" name="sondage" value="'.$numsondageadmin.'">';
+	print '<input type="hidden" name="backtourl" value="'.GETPOST('backtourl').'">';
+
+	print '<div class="center">'."\n";
+	print "<br><br>"."\n";
+
+	// Add new column
+	if ($object->format=="A"||$object->format=="A+")
+	{
+		print $langs->trans("AddNewColumn") .' :<br><br>';
+		print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>';
+		$tmparray=array('checkbox'=>$langs->trans("CheckBox"),'yesno'=>$langs->trans("YesNoList"),'foragainst'=>$langs->trans("PourContreList"));
+		print $langs->trans("Type").' '.$form->selectarray("typecolonne", $tmparray, GETPOST('typecolonne')).'<br><br>';
+		print '<input type="submit" class="button" name="ajoutercolonne" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
+		print ' &nbsp; &nbsp; ';
+		print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
+		print '<br><br>'."\n";
+	}
+	else
+	{
+		//ajout d'une date avec creneau horaire
+		//print _("You can add a new scheduling date to your poll.<br> If you just want to add a new hour to an existant date, put the same date and choose a new hour.") .'<br><br> '."\n";
+		print $langs->trans("AddADate") .' :<br><br>'."\n";
+		print '<select name="nouveaujour"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		for ($i=1;$i<32;$i++){
+			print '<OPTION VALUE="'.$i.'">'.$i.'</OPTION>'."\n";
+		}
+		print '</SELECT>'."\n";
+
+		print '<select name="nouveaumois"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		for($i = 1; $i < 13; $i++) {
+			print '<OPTION VALUE="'.$i.'">'.strftime('%B', mktime(0, 0, 0, $i)).'</OPTION>'."\n";
+		}
+		print '</SELECT>'."\n";
+
+
+		print '<select name="nouvelleannee"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		for ($i = date("Y"); $i < (date("Y") + 5); $i++) {
+			print '<OPTION VALUE="'.$i.'">'.$i.'</OPTION>'."\n";
+		}
+		print '</SELECT>'."\n";
+		print '<br><br>'. $langs->trans("AddStartHour") .' : <br><br>'."\n";
+		print '<select name="nouvelleheuredebut"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		for ($i = 0; $i < 24; $i++) {
+			print '<OPTION VALUE="'.$i.'">'.$i.' H</OPTION>'."\n";
+		}
+		print '</SELECT>'."\n";
+		print '<select name="nouvelleminutedebut"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		print '<OPTION VALUE="00">00</OPTION>'."\n";
+		print '<OPTION VALUE="15">15</OPTION>'."\n";
+		print '<OPTION VALUE="30">30</OPTION>'."\n";
+		print '<OPTION VALUE="45">45</OPTION>'."\n";
+		print '</SELECT>'."\n";
+		print '<br><br>'. $langs->trans("AddEndHour") .' : <br><br>'."\n";
+		print '<select name="nouvelleheurefin"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		for ($i = 0; $i < 24; $i++) {
+			print '<OPTION VALUE="'.$i.'">'.$i.' H</OPTION>'."\n";
+		}
+		print '</SELECT>'."\n";
+		print '<select name="nouvelleminutefin"> '."\n";
+		print '<OPTION VALUE="vide"></OPTION>'."\n";
+		print '<OPTION VALUE="00">00</OPTION>'."\n";
+		print '<OPTION VALUE="15">15</OPTION>'."\n";
+		print '<OPTION VALUE="30">30</OPTION>'."\n";
+		print '<OPTION VALUE="45">45</OPTION>'."\n";
+		print '</SELECT>'."\n";
+
+		print '<br><br>';
+		print' <input type="submit" class="button" name="ajoutercolonne" value="'.dol_escape_htmltag($langs->trans("Add")).'">'."\n";
+		print '&nbsp; &nbsp;';
+		print '<input type="submit" class="button" name="retoursondage" value="'.$langs->trans("Cancel").'">';
+	}
+
+	print '</form>'."\n";
+	print '<br><br><br><br>'."\n";
+	print '</div>'."\n";
+
+	exit;
+}
+
+
+print $langs->trans("PollAdminDesc",img_picto('','cancel.png@opensurvey'),img_picto('','add-16.png@opensurvey')).'<br><br>';
+
+print '<div class="corps"> '."\n";
+
+//affichage du titre du sondage
+$titre=str_replace("\\","",$object->titre);
+print '<strong>'.$titre.'</strong><br>'."\n";
+
+//affichage du nom de l'auteur du sondage
+print $langs->trans("InitiatorOfPoll") .' : '.$object->nom_admin.'<br>'."\n";
+
+//affichage des commentaires du sondage
+if ($object->commentaires)
+{
+	print '<br>'.$langs->trans("Description") .' :<br>'."\n";
+	$commentaires=dol_nl2br($object->commentaires);
+	print $commentaires;
+	print '<br>'."\n";
+}
+
+print '</div>'."\n";
+
+
+$nbcolonnes=substr_count($object->sujet,',')+1;
+
+print '<form name="formulaire" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
+print '<input type="hidden" name="sondage" value="'.$numsondageadmin.'">';
+
+print '<div class="cadre"> '."\n";
+print '<br>'."\n";
+
+//debut de l'affichage de résultats
+print '<table class="resultats">'."\n";
+
+//reformatage des données des sujets du sondage
+$toutsujet=explode(",",$object->sujet);
+$toutsujet=str_replace("°","'",$toutsujet);
+
+print '<tr>'."\n";
+print '<td></td>'."\n";
+print '<td></td>'."\n";
+
+//boucle pour l'affichage des boutons de suppression de colonne
+for ($i = 0; isset($toutsujet[$i]); $i++) {
+	print '<td class=somme><input type="image" name="effacecolonne'.$i.'" value="Effacer la colonne" src="'.dol_buildpath('/opensurvey/img/cancel.png',1).'"></td>'."\n";
+}
+
+print '</tr>'."\n";
+
+
+// Show choice titles
+if ($object->format=="D"||$object->format=="D+")
+{
+	//affichage des sujets du sondage
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des années
+	$colspan=1;
+	for ($i=0;$i<count($toutsujet);$i++)
+	{
+		$current = $toutsujet[$i];
+
+		if (strpos($toutsujet[$i], '@') !== false) {
+			$current = substr($toutsujet[$i], 0, strpos($toutsujet[$i], '@'));
+		}
+
+		if (isset($toutsujet[$i+1]) && strpos($toutsujet[$i+1], '@') !== false) {
+			$next = substr($toutsujet[$i+1], 0, strpos($toutsujet[$i+1], '@'));
+		} elseif (isset($toutsujet[$i+1])) {
+			$next = $toutsujet[$i+1];
+		}
+
+		if (isset($toutsujet[$i+1]) && strftime("%Y",$current) == strftime("%Y",$next)){
+			$colspan++;
+		} else {
+			print '<td colspan='.$colspan.' class="annee">'.strftime("%Y", $current).'</td>'."\n";
+			$colspan=1;
+		}
+	}
+
+	print '<td class="annee"><a href="'.$_SERVER["PHP_SELF"].'?ajoutsujet=1&sondage='.$object->id_sondage_admin.'">'.$langs->trans("Add").'</a></td>'."\n";
+	print '</tr>'."\n";
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des mois
+	$colspan = 1;
+	for ($i = 0; $i < count($toutsujet); $i++) {
+		$cur = intval($toutsujet[$i]);	// intval() est utiliser pour supprimer le suffixe @* qui déplaît logiquement à strftime()
+
+		if (isset($toutsujet[$i+1]) === false) {
+			$next = false;
+		} else {
+			$next = intval($toutsujet[$i+1]);
+		}
+
+		if ($next && dol_print_date($cur, "%B") == dol_print_date($next, "%B") && dol_print_date($cur, "%Y") == dol_print_date($next, "%Y")){
+			$colspan++;
+		} else {
+			print '<td colspan='.$colspan.' class="mois">'.dol_print_date($cur, "%B").'</td>'."\n";
+
+			$colspan=1;
+		}
+	}
+
+	print '<td class="mois"><a href="'.$_SERVER["PHP_SELF"].'?ajoutsujet=1&sondage='.$object->id_sondage_admin.'">'.$langs->trans("Add").'</a></td>'."\n";
+	print '</tr>'."\n";
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des jours
+	$colspan = 1;
+	for ($i = 0; $i < count($toutsujet); $i++) {
+		$cur = intval($toutsujet[$i]);
+		if (isset($toutsujet[$i+1]) === false) {
+			$next = false;
+		} else {
+			$next = intval($toutsujet[$i+1]);
+		}
+		if ($next && dol_print_date($cur, "%a %e") == dol_print_date($next,"%a %e") && dol_print_date($cur, "%B") == dol_print_date($next, "%B")) {
+			$colspan++;
+		} else {
+			print '<td colspan='.$colspan.' class="jour">'.dol_print_date($cur, "%a %e").'</td>'."\n";
+
+			$colspan=1;
+		}
+	}
+
+	print '<td class="jour"><a href="'.$_SERVER["PHP_SELF"].'?ajoutsujet=1&sondage='.$object->id_sondage_admin.'">'.$langs->trans("Add").'</a></td>'."\n";
+	print '</tr>'."\n";
+
+	//affichage des horaires
+	if (strpos($object->sujet,'@') !== false) {
+		print '<tr>'."\n";
+		print '<td></td>'."\n";
+		print '<td></td>'."\n";
+
+		for ($i = 0; isset($toutsujet[$i]); $i++) {
+			$heures=explode('@', $toutsujet[$i]);
+			if (isset($heures[1])) {
+				print '<td class="heure">'.$heures[1].'</td>'."\n";
+			} else {
+				print '<td class="heure"></td>'."\n";
+			}
+		}
+
+		print '<td class="heure"><a href="'.$_SERVER["PHP_SELF"].'?ajoutsujet=1&sondage='.$object->id_sondage_admin.'">'.$langs->trans("Add").'</a></td>'."\n";
+		print '</tr>'."\n";
+	}
+}
+else
+{
+	//affichage des sujets du sondage
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td></td>'."\n";
+
+	for ($i = 0; isset($toutsujet[$i]); $i++)
+	{
+		$tmp=explode('@',$toutsujet[$i]);
+		print '<td class="sujet">'.$tmp[0].'</td>'."\n";
+	}
+
+	print '<td class="sujet"><a href="'.$_SERVER["PHP_SELF"].'?sondage='.$numsondageadmin.'&ajoutsujet=1&backtourl='.urlencode($_SERVER["PHP_SELF"].'?sondage='.$numsondageadmin).'">'.img_picto('',dol_buildpath('/opensurvey/img/add-16.png',1),'',1).'</a></td>'."\n";
+	print '</tr>'."\n";
+}
+
+
+// Loop on each answer
+$sumfor = array();
+$sumagainst = array();
+$compteur = 0;
+$sql ="SELECT id_users, nom, id_sondage, reponses";
+$sql.=" FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
+$sql.=" WHERE id_sondage = '".$db->escape($numsondage)."'";
+dol_syslog('sql='.$sql);
+$resql=$db->query($sql);
+if (! $resql)
+{
+	dol_print_error($db);
+	exit;
+}
+$num=$db->num_rows($resql);
+while ($compteur < $num)
+{
+	$obj=$db->fetch_object($resql);
+
+	$ensemblereponses = $obj->reponses;
+
+	print '<tr>'."\n";
+	print '<td><input type="image" name="effaceligne'.$compteur.'" value="Effacer" src="'.dol_buildpath('/opensurvey/img/cancel.png',1).'"></td>'."\n";
+
+	// Name
+	$nombase=str_replace("°","'",$obj->nom);
+	print '<td class="nom">'.$nombase.'</td>'."\n";
+
+	// si la ligne n'est pas a changer, on affiche les données
+	if (! $testligneamodifier)
+	{
+		for ($i = 0; $i < $nbcolonnes; $i++)
+		{
+			$car = substr($ensemblereponses, $i, 1);
+			//print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz';
+
+			if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+			{
+				if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n";
+				else print '<td class="non">KO</td>'."\n";
+				// Total
+				if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+			{
+				if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n";
+				else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n";
+				else print '<td class="vide">&nbsp;</td>'."\n";
+				// Total
+				if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+				if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+				if (((string) $car) == "0") $sumagainst[$i]++;
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+			{
+				if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
+				else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
+				else print '<td class="vide">&nbsp;</td>'."\n";
+				// Total
+				if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+				if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+				if (((string) $car) == "0") $sumagainst[$i]++;
+			}
+		}
+	}
+	else
+	{
+		//sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs
+		if ($compteur == $ligneamodifier)
+		{
+			for ($i = 0; $i < $nbcolonnes; $i++)
+			{
+				$car = substr($ensemblereponses, $i, 1);
+				print '<td class="vide">';
+				if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+				{
+					print '<input type="checkbox" name="choix'.$i.'" value="1" ';
+					if ($car == '1') print 'checked="checked"';
+					print '>';
+				}
+				if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+				{
+					$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes"));
+					print $form->selectarray("choix".$i, $arraychoice, $car);
+				}
+				if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+				{
+					$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("Against"),'1'=>$langs->trans("For"));
+					print $form->selectarray("choix".$i, $arraychoice, $car);
+				}
+				print '</td>'."\n";
+			}
+		}
+		else
+		{
+			for ($i = 0; $i < $nbcolonnes; $i++)
+			{
+				$car = substr($ensemblereponses, $i, 1);
+				if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+				{
+					if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n";
+					else print '<td class="non">KO</td>'."\n";
+					// Total
+					if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+					if (((string) $car) == "1") $sumfor[$i]++;
+				}
+				if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+				{
+					if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
+					else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
+					else print '<td class="vide">&nbsp;</td>'."\n";
+					// Total
+					if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+					if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+					if (((string) $car) == "1") $sumfor[$i]++;
+					if (((string) $car) == "0") $sumagainst[$i]++;
+				}
+				if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+				{
+					if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
+					else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
+					else print '<td class="vide">&nbsp;</td>'."\n";
+					// Total
+					if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+					if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+					if (((string) $car) == "1") $sumfor[$i]++;
+					if (((string) $car) == "0") $sumagainst[$i]++;
+				}
+			}
+		}
+	}
+
+	//a la fin de chaque ligne se trouve les boutons modifier
+	if ($compteur != $ligneamodifier)
+	{
+		print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n";
+	}
+
+	//demande de confirmation pour modification de ligne
+	for ($i = 0; $i < $nblignes; $i++)
+	{
+		if (isset($_POST["modifierligne".$i]))
+		{
+			if ($compteur == $i)
+			{
+				print '<td class="casevide">';
+				print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">';
+				print '<input type="submit" class="button" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
+				print '</td>'."\n";
+			}
+		}
+	}
+
+	$compteur++;
+	print '</tr>'."\n";
+}
+
+// Add line to add new record
+if (empty($testligneamodifier))
+{
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td class="nom">'."\n";
+	print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n";
+	print '</td>'."\n";
+
+	for ($i = 0; $i < $nbcolonnes; $i++)
+	{
+		print '<td class="vide">';
+		if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+		{
+			print '<input type="checkbox" name="choix'.$i.'" value="1"';
+			if ( isset($_POST['choix'.$i]) && $_POST['choix'.$i] == '1' && is_error(NAME_EMPTY) )
+			{
+				print ' checked="checked"';
+			}
+			print '>';
+		}
+		if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+		{
+			$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes"));
+			print $form->selectarray("choix".$i, $arraychoice);
+		}
+		if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+		{
+			$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("Against"),'1'=>$langs->trans("For"));
+			print $form->selectarray("choix".$i, $arraychoice);
+		}
+		print '</td>'."\n";
+	}
+
+	// Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base
+	print '<td><input type="image" name="boutonp" value="'.$langs->trans("Vote").'" src="'.dol_buildpath('/opensurvey/img/add-24.png',1).'"></td>'."\n";
+	print '</tr>'."\n";
+}
+
+// Select value of best choice (for checkbox columns only)
+$nbofcheckbox=0;
+for ($i=0; $i < $nbcolonnes + 1; $i++)
+{
+	if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+	$nbofcheckbox++;
+	if (isset($sumfor[$i]))
+	{
+		if ($i == 0) {
+			$meilleurecolonne = $sumfor[$i];
+		}
+		if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne){
+			$meilleurecolonne = $sumfor[$i];
+		}
+	}
+}
+
+
+// Show line total
+print '<tr>'."\n";
+print '<td></td>'."\n";
+print '<td align="center">'. $langs->trans("Total") .'</td>'."\n";
+for ($i = 0; $i < $nbcolonnes; $i++)
+{
+	$showsumfor = isset($sumfor[$i])?$sumfor[$i]:'';
+	$showsumagainst = isset($sumagainst[$i])?$sumagainst[$i]:'';
+	if (empty($showsumfor)) $showsumfor = 0;
+	if (empty($showsumagainst)) $showsumagainst = 0;
+
+	print '<td>';
+	if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst'))) print $showsumfor;
+	if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst;
+	if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst;
+	print '</td>'."\n";
+}
+print '</tr>';
+// Show picto winner
+if ($nbofcheckbox >= 2)
+{
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+	print '<td></td>'."\n";
+	for ($i = 0; $i < $nbcolonnes; $i++) {
+		if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')) && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne)
+		{
+			print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png',1).'"></td>'."\n";
+		} else {
+			print '<td class="somme"></td>'."\n";
+		}
+	}
+	print '</tr>'."\n";
+}
+
+// S'il a oublié de remplir un nom
+if ((isset($_POST["boutonp"]) || isset($_POST["boutonp_x"])) && $_POST["nom"] == "") {
+	print '<tr>'."\n";
+	print "<td colspan=10><font color=#FF0000>" . _("Enter a name !") . "</font>\n";
+	print '</tr>'."\n";
+}
+
+if (isset($erreur_prenom) && $erreur_prenom) {
+	print '<tr>'."\n";
+	print "<td colspan=10><font color=#FF0000>" . _("The name you've chosen already exist in this poll!") . "</font></td>\n";
+	print '</tr>'."\n";
+}
+
+if (isset($erreur_injection) && $erreur_injection) {
+	print '<tr>'."\n";
+	print "<td colspan=10><font color=#FF0000>" . _("Characters \"  '  < et > are not permitted") . "</font></td>\n";
+	print '</tr>'."\n";
+}
+
+if (isset($erreur_ajout_date) && $erreur_ajout_date) {
+	print '<tr>'."\n";
+	print "<td colspan=10><font color=#FF0000>" . _("The date is not correct !") . "</font></td>\n";
+	print '</tr>'."\n";
+}
+
+//fin du tableau
+print '</table>'."\n";
+print '</div>'."\n";
+
+
+$toutsujet = explode(",", $object->sujet);
+
+$compteursujet = 0;
+$meilleursujet = '';
+for ($i = 0; $i < $nbcolonnes; $i++) {
+	if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne){
+		$meilleursujet.=", ";
+
+		if ($object->format == "D" || $object->format == "D+") {
+			$meilleursujetexport = $toutsujet[$i];
+
+			if (strpos($toutsujet[$i], '@') !== false) {
+				$toutsujetdate = explode("@", $toutsujet[$i]);
+				$meilleursujet .= dol_print_date($toutsujetdate[0],'daytext'). ' ('.dol_print_date($toutsujetdate[0],'%A').')' . ' - ' . $toutsujetdate[1];
+			} else {
+				$meilleursujet .= dol_print_date($toutsujet[$i],'daytext'). ' ('.dol_print_date($toutsujet[$i],'%A').')';
+			}
+		}
+		else
+		{
+			$tmps=explode('@',$toutsujet[$i]);
+			$meilleursujet .= $tmps[0];
+		}
+
+		$compteursujet++;
+	}
+}
+
+//adaptation pour affichage des valeurs
+$meilleursujet = substr("$meilleursujet", 1);
+$meilleursujet = str_replace("°", "'", $meilleursujet);
+
+// Show best choice
+if ($nbofcheckbox >= 2)
+{
+	$vote_str = $langs->trans('votes');
+	print '<p class=affichageresultats>'."\n";
+
+	if (isset($meilleurecolonne) && $compteursujet == "1") {
+		print "<img src=\"".dol_buildpath('/opensurvey/img/medaille.png',1)."\"> " . $langs->trans('TheBestChoice') . " : <b>$meilleursujet </b>" . $langs->trans("with") . " <b>$meilleurecolonne </b>" . $vote_str . ".<br>\n";
+	} elseif (isset($meilleurecolonne)) {
+		print "<img src=\"".dol_buildpath('/opensurvey/img/medaille.png',1)."\"> " . $langs->trans('TheBestChoices') . " : <b>$meilleursujet </b>" . $langs->trans("with") . " <b>$meilleurecolonne </b>" . $vote_str . ".<br>\n";
+	}
+	print '</p><br>'."\n";
+}
+
+print '</form>'."\n";
+
+llxFooterSurvey();
+
+$db->close();
+?>
diff --git a/htdocs/opensurvey/class/opensurveysondage.class.php b/htdocs/opensurvey/class/opensurveysondage.class.php
new file mode 100644
index 0000000000000000000000000000000000000000..0a3f2c571df62112b8d9eee22f15b7694b2cccb4
--- /dev/null
+++ b/htdocs/opensurvey/class/opensurveysondage.class.php
@@ -0,0 +1,512 @@
+<?php
+/* Copyright (C) 2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       dev/skeletons/opensurveysondage.class.php
+ *  \ingroup    mymodule othermodule1 othermodule2
+ *  \brief      This file is an example for a CRUD class file (Create/Read/Update/Delete)
+ *				Initialy built by build_class_from_table on 2013-03-10 00:32
+ */
+
+// Put here all includes required by your class file
+require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php");
+//require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
+//require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php");
+
+
+/**
+ *	Put here description of your class
+ */
+class Opensurveysondage extends CommonObject
+{
+	var $db;							//!< To store db handler
+	var $error;							//!< To return error code (or message)
+	var $errors=array();				//!< To return several error codes (or messages)
+	var $element='opensurvey_sondage';			//!< Id that identify managed objects
+	var $table_element='opensurvey_sondage';	//!< Name of table without prefix where object is stored
+
+    var $id;
+
+	var $id_sondage;
+	var $commentaires;
+	var $mail_admin;
+	var $nom_admin;
+	var $titre;
+	var $id_sondage_admin;
+	var $date_fin='';
+	var $format;
+	var $mailsonde;
+	var $survey_link_visible;
+	var $canedit;
+
+
+
+
+    /**
+     *  Constructor
+     *
+     *  @param	DoliDb		$db      Database handler
+     */
+    function __construct($db)
+    {
+        $this->db = $db;
+        return 1;
+    }
+
+
+    /**
+     *  Create object into database
+     *
+     *  @param	User	$user        User that creates
+     *  @param  int		$notrigger   0=launch triggers after, 1=disable triggers
+     *  @return int      		   	 <0 if KO, Id of created object if OK
+     */
+    function create($user, $notrigger=0)
+    {
+    	global $conf, $langs;
+		$error=0;
+
+		// Clean parameters
+
+		if (isset($this->id_sondage)) $this->id_sondage=trim($this->id_sondage);
+		if (isset($this->commentaires)) $this->commentaires=trim($this->commentaires);
+		if (isset($this->mail_admin)) $this->mail_admin=trim($this->mail_admin);
+		if (isset($this->nom_admin)) $this->nom_admin=trim($this->nom_admin);
+		if (isset($this->titre)) $this->titre=trim($this->titre);
+		if (isset($this->id_sondage_admin)) $this->id_sondage_admin=trim($this->id_sondage_admin);
+		if (isset($this->format)) $this->format=trim($this->format);
+		if (isset($this->mailsonde)) $this->mailsonde=trim($this->mailsonde);
+		if (isset($this->survey_link_visible)) $this->survey_link_visible=trim($this->survey_link_visible);
+		if (isset($this->canedit)) $this->canedit=trim($this->canedit);
+
+
+
+		// Check parameters
+		// Put here code to add control on parameters values
+
+        // Insert request
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_sondage(";
+
+		$sql.= "id_sondage,";
+		$sql.= "commentaires,";
+		$sql.= "mail_admin,";
+		$sql.= "nom_admin,";
+		$sql.= "titre,";
+		$sql.= "id_sondage_admin,";
+		$sql.= "date_fin,";
+		$sql.= "format,";
+		$sql.= "mailsonde,";
+		$sql.= "survey_link_visible,";
+		$sql.= "canedit";
+        $sql.= ") VALUES (";
+
+		$sql.= " ".(! isset($this->id_sondage)?'NULL':"'".$this->id_sondage."'").",";
+		$sql.= " ".(! isset($this->commentaires)?'NULL':"'".$this->db->escape($this->commentaires)."'").",";
+		$sql.= " ".(! isset($this->mail_admin)?'NULL':"'".$this->db->escape($this->mail_admin)."'").",";
+		$sql.= " ".(! isset($this->nom_admin)?'NULL':"'".$this->db->escape($this->nom_admin)."'").",";
+		$sql.= " ".(! isset($this->titre)?'NULL':"'".$this->db->escape($this->titre)."'").",";
+		$sql.= " ".(! isset($this->id_sondage_admin)?'NULL':"'".$this->id_sondage_admin."'").",";
+		$sql.= " ".(! isset($this->date_fin) || dol_strlen($this->date_fin)==0?'NULL':$this->db->idate($this->date_fin)).",";
+		$sql.= " ".(! isset($this->format)?'NULL':"'".$this->db->escape($this->format)."'").",";
+		$sql.= " ".(! isset($this->mailsonde)?'NULL':"'".$this->mailsonde."'").",";
+		$sql.= " ".(! isset($this->survey_link_visible)?'NULL':"'".$this->survey_link_visible."'").",";
+		$sql.= " ".(! isset($this->canedit)?'NULL':"'".$this->canedit."'")."";
+
+		$sql.= ")";
+
+		$this->db->begin();
+
+	   	dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
+        $resql=$this->db->query($sql);
+    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
+
+		if (! $error)
+        {
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."opensurvey_sondage");
+
+			if (! $notrigger)
+			{
+	            // Uncomment this and change MYOBJECT to your own tag if you
+	            // want this action calls a trigger.
+
+	            //// Call triggers
+	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
+	            //$interface=new Interfaces($this->db);
+	            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
+	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
+	            //// End call triggers
+			}
+        }
+
+        // Commit or rollback
+        if ($error)
+		{
+			foreach($this->errors as $errmsg)
+			{
+	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
+	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+			}
+			$this->db->rollback();
+			return -1*$error;
+		}
+		else
+		{
+			$this->db->commit();
+            return $this->id;
+		}
+    }
+
+
+    /**
+     *  Load object in memory from the database
+     *
+     *  @param	int		$id    				Id object
+     *  @param	string	$numsurvey			Ref of survey (admin or not)
+     *  @return int          				<0 if KO, >0 if OK
+     */
+    function fetch($id,$numsurvey='')
+    {
+    	global $langs;
+
+    	$sql = "SELECT";
+		//$sql.= " t.rowid,";
+		$sql.= " t.id_sondage,";
+		$sql.= " t.commentaires,";
+		$sql.= " t.mail_admin,";
+		$sql.= " t.nom_admin,";
+		$sql.= " t.titre,";
+		$sql.= " t.id_sondage_admin,";
+		$sql.= " t.date_fin,";
+		$sql.= " t.format,";
+		$sql.= " t.mailsonde,";
+		$sql.= " t.survey_link_visible,";
+		$sql.= " t.canedit,";
+		$sql.= " t.sujet,";
+		$sql.= " t.tms";
+        $sql.= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as t";
+        if ($id > 0) $sql.= " WHERE t.rowid = ".$id;
+        else if (strlen($numsurvey) == 16) $sql.= " WHERE t.id_sondage = '".$numsurvey."'";
+        else $sql.= " WHERE t.id_sondage_admin = '".$numsurvey."'";
+
+    	dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
+        $resql=$this->db->query($sql);
+        if ($resql)
+        {
+            if ($this->db->num_rows($resql))
+            {
+                $obj = $this->db->fetch_object($resql);
+
+                //$this->id  = $obj->rowid;
+				$this->ref = $obj->id_sondage_admin;
+
+				$this->id_sondage = $obj->id_sondage;
+				$this->commentaires = $obj->commentaires;
+				$this->mail_admin = $obj->mail_admin;
+				$this->nom_admin = $obj->nom_admin;
+				$this->titre = $obj->titre;
+				$this->id_sondage_admin = $obj->id_sondage_admin;
+				$this->date_fin = $this->db->jdate($obj->date_fin);
+				$this->format = $obj->format;
+				$this->mailsonde = $obj->mailsonde;
+				$this->survey_link_visible = $obj->survey_link_visible;
+				$this->canedit = $obj->canedit;
+				$this->sujet = $obj->sujet;
+
+				$this->date_m = $this->db->jdate($obj->tls);
+				$ret=1;
+            }
+            else $ret=0;
+
+            $this->db->free($resql);
+        }
+        else
+       {
+      	    $this->error="Error ".$this->db->lasterror();
+            dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
+            $ret=-1;
+        }
+
+        return $ret;
+    }
+
+
+    /**
+     *  Update object into database
+     *
+     *  @param	User	$user        User that modifies
+     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
+     *  @return int     		   	 <0 if KO, >0 if OK
+     */
+    function update($user=0, $notrigger=0)
+    {
+    	global $conf, $langs;
+		$error=0;
+
+		// Clean parameters
+
+		if (isset($this->id_sondage)) $this->id_sondage=trim($this->id_sondage);
+		if (isset($this->commentaires)) $this->commentaires=trim($this->commentaires);
+		if (isset($this->mail_admin)) $this->mail_admin=trim($this->mail_admin);
+		if (isset($this->nom_admin)) $this->nom_admin=trim($this->nom_admin);
+		if (isset($this->titre)) $this->titre=trim($this->titre);
+		if (isset($this->id_sondage_admin)) $this->id_sondage_admin=trim($this->id_sondage_admin);
+		if (isset($this->format)) $this->format=trim($this->format);
+		if (isset($this->mailsonde)) $this->mailsonde=trim($this->mailsonde);
+		if (isset($this->survey_link_visible)) $this->survey_link_visible=trim($this->survey_link_visible);
+		if (isset($this->canedit)) $this->canedit=trim($this->canedit);
+
+
+		// Check parameters
+		// Put here code to add a control on parameters values
+
+        // Update request
+        $sql = "UPDATE ".MAIN_DB_PREFIX."opensurvey_sondage SET";
+
+		$sql.= " id_sondage='".(isset($this->id_sondage)?$this->id_sondage:"null")."',";
+		$sql.= " commentaires=".(isset($this->commentaires)?"'".$this->db->escape($this->commentaires)."'":"null").",";
+		$sql.= " mail_admin=".(isset($this->mail_admin)?"'".$this->db->escape($this->mail_admin)."'":"null").",";
+		$sql.= " nom_admin=".(isset($this->nom_admin)?"'".$this->db->escape($this->nom_admin)."'":"null").",";
+		$sql.= " titre=".(isset($this->titre)?"'".$this->db->escape($this->titre)."'":"null").",";
+		$sql.= " id_sondage_admin='".(isset($this->id_sondage_admin)?$this->id_sondage_admin:"null")."',";
+		$sql.= " date_fin=".(dol_strlen($this->date_fin)!=0 ? "'".$this->db->idate($this->date_fin)."'" : 'null').",";
+		$sql.= " format=".(isset($this->format)?"'".$this->db->escape($this->format)."'":"null").",";
+		$sql.= " mailsonde=".(isset($this->mailsonde)?$this->mailsonde:"null").",";
+		$sql.= " survey_link_visible=".(isset($this->survey_link_visible)?$this->survey_link_visible:"null").",";
+		$sql.= " canedit=".(isset($this->canedit)?$this->canedit:"null")."";
+
+        //$sql.= " WHERE rowid=".$this->id;
+		$sql.= " WHERE id_sondage_admin='".$this->id_sondage_admin."'";
+
+		$this->db->begin();
+
+		dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
+        $resql = $this->db->query($sql);
+    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
+
+		if (! $error)
+		{
+			if (! $notrigger)
+			{
+	            // Uncomment this and change MYOBJECT to your own tag if you
+	            // want this action calls a trigger.
+
+	            //// Call triggers
+	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
+	            //$interface=new Interfaces($this->db);
+	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
+	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
+	            //// End call triggers
+	    	}
+		}
+
+        // Commit or rollback
+		if ($error)
+		{
+			foreach($this->errors as $errmsg)
+			{
+	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
+	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+			}
+			$this->db->rollback();
+			return -1*$error;
+		}
+		else
+		{
+			$this->db->commit();
+			return 1;
+		}
+    }
+
+
+ 	/**
+	 *  Delete object in database
+	 *
+     *	@param  User	$user        		User that deletes
+     *  @param  int		$notrigger	 		0=launch triggers after, 1=disable triggers
+     *  @param	string	$numsondageadmin	Num sondage to delete
+	 *  @return	int					 		<0 if KO, >0 if OK
+	 */
+	function delete($user, $notrigger, $numsondageadmin)
+	{
+		global $conf, $langs;
+		$error=0;
+
+		$this->db->begin();
+
+		if (! $error)
+		{
+			if (! $notrigger)
+			{
+				// Uncomment this and change MYOBJECT to your own tag if you
+		        // want this action calls a trigger.
+
+		        //// Call triggers
+		        //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
+		        //$interface=new Interfaces($this->db);
+		        //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
+		        //if ($result < 0) { $error++; $this->errors=$interface->errors; }
+		        //// End call triggers
+			}
+		}
+
+		if (! $error)
+		{
+
+			$sql='DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage_admin = '".$numsondageadmin."'";
+			dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG);
+			$resql=$this->db->query($sql);
+			$sql='DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage_admin = '".$numsondageadmin."'";
+			dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG);
+			$resql=$this->db->query($sql);
+
+    		$sql = "DELETE FROM ".MAIN_DB_PREFIX."opensurvey_sondage";
+    		$sql.= " WHERE id_sondage_admin = '".$numsondageadmin."'";
+
+    		dol_syslog(get_class($this)."::delete sql=".$sql);
+    		$resql = $this->db->query($sql);
+        	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
+		}
+
+        // Commit or rollback
+		if ($error)
+		{
+			foreach($this->errors as $errmsg)
+			{
+	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
+	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+			}
+			$this->db->rollback();
+			return -1*$error;
+		}
+		else
+		{
+			$this->db->commit();
+			return 1;
+		}
+	}
+
+	/**
+	 * Return array of lines
+	 *
+	 * @return 	array	Array of lines
+	 */
+	function fetch_lines()
+	{
+		$ret=array();
+		$sql = "SELECT id_users, nom, reponses FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
+		$sql.= " WHERE id_sondage = '".$this->id_sondage."'";
+		$resql=$this->db->query($sql);
+
+		if ($resql)
+		{
+			$num=$this->db->num_rows($resql);
+			$i=0;
+			while ($i < $num)
+			{
+				$obj=$this->db->fetch_object($resql);
+				$tmp=array('id_users'=>$obj->id_users, 'nom'=>$obj->nom, 'reponses'=>$obj->reponses);
+
+				$ret[]=$tmp;
+				$i++;
+			}
+		}
+		else dol_print_error($this->db);
+
+		$this->lines=$ret;
+
+		return $this->lines;
+	}
+
+	/**
+	 *	Load an object from its id and create a new one in database
+	 *
+	 *	@param	int		$fromid     Id of object to clone
+	 * 	@return	int					New id of clone
+	 */
+	function createFromClone($fromid)
+	{
+		global $user,$langs;
+
+		$error=0;
+
+		$object=new Opensurveysondage($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$object->fetch($fromid);
+		$object->id=0;
+		$object->statut=0;
+
+		// Clear fields
+		// ...
+
+		// Create clone
+		$result=$object->create($user);
+
+		// Other options
+		if ($result < 0)
+		{
+			$this->error=$object->error;
+			$error++;
+		}
+
+		if (! $error)
+		{
+
+
+		}
+
+		// End
+		if (! $error)
+		{
+			$this->db->commit();
+			return $object->id;
+		}
+		else
+		{
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+
+	/**
+	 *	Initialise object with example values
+	 *	Id must be 0 if object instance is a specimen
+	 *
+	 *	@return	void
+	 */
+	function initAsSpecimen()
+	{
+		$this->id=0;
+
+		$this->id_sondage='';
+		$this->commentaires='';
+		$this->mail_admin='';
+		$this->nom_admin='';
+		$this->titre='';
+		$this->id_sondage_admin='';
+		$this->date_fin='';
+		$this->format='';
+		$this->mailsonde='';
+		$this->survey_link_visible='';
+		$this->canedit=0;
+	}
+
+}
+?>
diff --git a/htdocs/opensurvey/css/style.css b/htdocs/opensurvey/css/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..be8e05df4c1ff023011366703899ebc3e26b5be9
--- /dev/null
+++ b/htdocs/opensurvey/css/style.css
@@ -0,0 +1,532 @@
+/* Copyright (C) 2004-2013	Laurent Destailleur		<eldy@users.sourceforge.net>
+ * Copyright (C) 2006		Rodolphe Quiedeville	<rodolphe@quiedeville.org>
+ * Copyright (C) 2007-2012	Regis Houssin			<regis.houssin@capnetworks.com>
+ * Copyright (C) 2011		Philippe Grand			<philippe.grand@atoo-net.com>
+ * Copyright (C) 2012		Juanjo Menent			<jmenent@2byte.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+.survey_invitation
+{
+	font-color: #445566;
+	font-weight: bold;
+}
+
+.corps {
+font-family: "Lucida Grande",Verdana,Arial,sans-serif;
+font-size: 14px;
+margin: auto;
+padding: 20px;
+overflow-x: auto;
+border: 2px solid #999999;
+background-color: #fff;
+box-shadow: 2px 2px 2px #F5F5F5;
+-moz-border-radius: 10px;
+border-radius: 10px;
+}
+
+
+.index_date, .index_sondage {
+float: left;
+width: 50%;
+text-align: center;
+}
+
+.orange {
+color: #fef4e9;
+border: solid 1px #da7c0c;
+background: #f78d1d;
+background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
+background: -moz-linear-gradient(top, #faa51a, #f47a20);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#faa51a', endColorstr='#f47a20');
+}
+.orange:active {
+color: #fcd3a5;
+background: -webkit-gradient(linear, left top, left bottom, from(#f47a20), to(#faa51a));
+background: -moz-linear-gradient(top, #f47a20, #faa51a);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f47a20', endColorstr='#faa51a');
+}
+.orange:hover {
+background: #f47c20;
+background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));
+background: -moz-linear-gradient(top, #f88e11, #f06015);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f88e11', endColorstr='#f06015');
+}
+
+
+.blue {
+color: #d9eef7;
+border: solid 1px #0076a3;
+background: #0095cd;
+background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
+background: -moz-linear-gradient(top, #00adee, #0078a5);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#0078a5');
+}
+.blue:active {
+color: #80bed6;
+background: -webkit-gradient(linear, left top, left bottom, from(#0078a5), to(#00adee));
+background: -moz-linear-gradient(top, #0078a5, #00adee);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0078a5', endColorstr='#00adee');
+}
+.blue:hover {
+background: #007ead;
+background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e));
+background: -moz-linear-gradient(top, #0095cc, #00678e);
+filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0095cc', endColorstr='#00678e');
+}
+
+
+/*
+==========================================================================
+
+Université de Strasbourg - Direction Informatique
+Auteur : Guilhem BORGHESI
+Création : Février 2008
+
+borghesi@unistra.fr
+
+Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
+respectant les principes de diffusion des logiciels libres. Vous pouvez
+utiliser, modifier et/ou redistribuer ce programme sous les conditions
+de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA 
+sur le site "http://www.cecill.info".
+
+Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
+pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
+termes. Vous pouvez trouver une copie de la licence dans le fichier LICENCE.
+
+==========================================================================
+
+Université de Strasbourg - Direction Informatique
+Author : Guilhem BORGHESI
+Creation : Feb 2008
+
+borghesi@unistra.fr
+
+This software is governed by the CeCILL-B license under French law and
+abiding by the rules of distribution of free software. You can  use, 
+modify and/ or redistribute the software under the terms of the CeCILL-B
+license as circulated by CEA, CNRS and INRIA at the following URL
+"http://www.cecill.info". 
+
+The fact that you are presently reading this means that you have had
+knowledge of the CeCILL-B license and that you accept its terms. You can
+find a copy of this license in the file LICENSE.
+
+==========================================================================
+*/
+
+/*
+Le fichier style.css est le fichier de style de studs. Il se trouve à la racine 
+du répertoire studs. Il contient toutes les mises en forme des fichiers PHP
+de Studs.
+*/
+/*bandeau de titre*/
+div.bandeau{ 
+	line-height:35px;
+	text-align:center;
+	background-color: #0b419b;
+	color:white;
+	vertical-align:middle;
+	font-size:35px;
+	font-family:arial;
+	padding:8px; 
+	height:35px;
+	position:static;
+	top:6px;
+	left:6px;
+	right:6px;
+
+}
+div.logo{ 
+	height:64px;
+	float:right;
+	top:8px;
+	right:8px;
+	margin-left: 0;
+	margin-right:0; 
+	margin-bottom:auto;
+}
+/*Sous bandeau avec bouton de navigation*/
+div.bandeautitre{ 
+	height:17px;
+	font-size:14px;
+	font-weight:bold;
+	text-align:center;
+	vertical-align:middle;
+	font-family:arial;
+ 	padding:3px; 
+	position:static;
+	top:57px;
+	left:6px;
+	right:6px;
+} 
+div.sousbandeau{ 
+	height:17px;
+	background-color: #DDDDDD;
+	font-size:11px;
+	color:black;
+	vertical-align:middle;
+	font-family:arial;
+	padding:3px;
+	position:static;
+	top:80px;
+	left:6px;
+	right:6px;
+}
+/*bandeau de pied*/
+div.surbandeaupied{ 
+	background-color: #0077DD;
+	position:absolute;
+	bottom:30px;
+	left:6px;
+	right:6px; 
+	height:6px;
+}
+div.bandeaupied{ 
+	text-align:center;
+	background-color: #0b419b;
+	color:white;
+	font-size:11px;
+	font-family:arial;
+	padding:6px;
+	position:fixed;
+	bottom:6px;
+	left:6px;
+	right:6px; 
+	margin:2px;
+}
+div.surbandeaupiedmobile{ 
+	background-color: #0077DD;
+	position:static; 
+	bottom:32px;
+	left:6px;
+	right:6px; 
+	height:6px;
+}
+div.bandeaupiedmobile{ 
+	text-align:center;
+	background-color: #0b419b;
+	color:white;
+	font-size:11px;
+	font-family:arial;
+	padding:6px; 
+	position:static; 
+}
+/*les boutons se trouvant dans le sousbandeau*/
+div.sousbandeau a, div.sousbandeau span.sousbandeaulangue a {
+ 	background-color: #0b419b; 
+	height:16px;
+	padding: 2px 6px 2px 6px;
+	vertical-align:middle;
+	text-align:center;
+	margin-left:10px;
+	margin-right:10px;
+	font-family:arial;
+	color:white;
+	font-size:10px;
+	text-decoration:none;
+}
+span.sousbandeaulangue {
+	margin-left:6px;
+	margin-right:6px;
+	float:right;
+}
+/*corps de la page index.php*/
+div.corps{ 
+	font-size:12px;
+	font-family:arial;
+	position:static;
+	padding:15px;
+}
+div.corps  table{
+	font-family:arial;
+	font-size:12px;	
+	font-weight:bold;
+}
+div.corpscentre{ 
+	font-size:12px;
+	font-family:arial;
+	text-align:center;
+	position:absolute;
+	top:150px;
+	margin-right:10%;
+	margin-left:10%;
+	width:80%;
+}
+/*affichage des jours*/
+div.jourschoisis {
+	background-color: #DDD;
+	padding:10px;
+	text-align: center;
+	position:static;
+	left:700px;
+	top:170px;
+	font-size:12px;
+	width:100%;
+}
+/*presenation des pages*/
+div.bodydate {
+	padding:10px;
+	font-family:arial;
+	font-size:12px;	
+	text-align:center;
+	position:static;
+	top:330px;
+	left:20px;
+	right:20px;
+}
+div.bodydate table{
+	font-family:arial;
+	font-size:12px;	
+	font-weight:bold;
+}
+/*cadre de commentaires*/
+div.presentationdate {
+	width:100%;
+	font-family:arial;
+	text-align:center;
+	font-size:12px;	
+	border-top:1px solid;
+	border-bottom:1px solid;
+	border-left: none;
+	border-right: none;
+	border-color:#969696;
+	position:static;
+	top:110px;
+	margin-top:10px;
+}
+div.presentationdatefin {
+	width:40%;
+	padding:10px;
+	font-family:arial;
+	text-align:center;
+	font-size:12px;	
+	border-width:1px;
+	border-style:solid;
+	margin-top: 10px;
+	margin-left: 30%;
+    margin-right: 30%; 
+	position:static;
+}
+/*cadre principal de studs.php*/
+div.cadre {
+	padding:10px; 
+	font-family:arial;
+	font-size:12px;	
+	position:static;
+	top:235px;
+	text-align:center;
+	margin:0 auto;
+}
+/*la table des résultats dans l'affichage de sondage*/
+div.cadre table.resultats {
+	text-align: center;
+	margin:0 auto;
+}
+td.nom {
+	min-width: 160px;
+}
+td.vide {
+	min-width: 60px;
+}
+div.cadre td {
+	height:21px;
+}
+/*case de tableau OK dans affichage de sondage*/
+div.cadre td.ok {
+	background-color: #66FF99; 
+	font-size:12px;	
+	text-align:center;
+}
+/*Case de tableau NON dans affichage de sondage*/
+div.cadre td.non {
+	background-color: #FF7777; 
+	min-width: 60px;
+}
+/*Case de tableau VIDE dans affichage de sondage*/
+div.cadre td.vide {
+	background-color: #DDDDDD; 
+	text-align:center;
+}
+/*Case de tableau contenant les noms dans affichage de sondage*/
+div.cadre td.nom {
+	background-color: #DDDDDD; 
+	font-size:12px;	 
+	text-align:center;
+}
+div.cadre td.casevide {
+	background-color: white; 
+	text-align:center;
+}
+/*les cases contenant les sommes de chaque colonne dans l'affichage de calendrier*/
+div.cadre td.somme {
+	font-weight:  bold;
+	font-size:14px; 
+}
+
+/*Case de tableau SUJET dans affichage de sondage*/
+div.cadre td.sujet, div.cadre td.jour, div.cadre td.heure {
+	border: 2px;
+	background-color: #DDDDDD; 
+	font-size:14px;
+	padding:1px 5px;
+}
+
+div.cadre td.annee {
+	border: 2px;
+	background-color: #969696; 
+	font-weight: bold;
+	font-size:14px;
+	padding:1px 5px;
+}
+div.cadre td.mois {
+	border: 2px;
+	background-color: #C0C0C0; 
+	font-weight: bold;
+	font-size:14px;
+	padding:1px 5px;
+}
+
+/*affichage du calendrier*/
+div.calendrier {
+	padding:10px;
+	background-color: #AAA;
+	width:490px;
+	font-size:12px;
+	font-family:arial;
+    margin-left: 30%;
+    margin-right: 30%;
+	position:static;
+}
+/*jour de la semaine dans calendrier*/
+div.calendrier td.joursemaine {
+	width:65px;
+	text-align: center;
+	font-family:arial;
+	font-size:14px;
+	border: 2px;
+	background-color: white; 
+}
+div.calendrier td.jourwe {
+	width:65px;
+	text-align: center;
+	font-family:arial;
+	font-size:14px;
+	border: 2px;
+	background-color: #C0C0C0; 
+}
+/*jour avant le premier jour du mois dans calendrier*/
+div.calendrier td.avant {
+	width:65px;
+	text-align: center;
+	border: 2px;
+	font-family:arial;
+	font-size:13px;
+	background-color: #DDDDDD; 
+}
+/*jour libre dans calendrier*/
+div.calendrier td.libre {
+	width:65px;
+	text-align: center;
+	border: 2px;
+	background-color: #66FF99; 
+}
+/*jour deja selectionné dans calendrier*/
+div.calendrier td.choisi {
+	width:65px;
+	text-align: center;
+	border: 2px;
+	background-color: #0077DD; 
+}
+/* Le paragraphe de fin */
+p.affichageresultats{
+	text-align: center;
+	font-family:arial;
+	font-size:13px;
+}
+
+div.comment{
+	width:100%;
+}
+
+div.comment span.usercomment{
+	font-weight:bold;
+}
+
+a.affichageexport{
+	text-align: center;
+	font-family:arial;
+	font-size:10px;
+	margin-left:10px;
+	text-decoration: none;
+}
+div.titregestionadmin{
+	text-align: center;
+	font-weight:bold;
+	font-size:18px;
+	padding:10px;
+}
+
+
+.bouton {
+	width: 65px;
+	border:0px;
+	padding:0px 0 0 0;
+	margin:0px;
+	cursor:pointer;
+	font-family:arial;
+	font-size:13px;
+}
+/*les boutons pour choisir un jour non selectionné*/
+.ON {
+    background-color: #BBBBCC;
+}
+
+/*les boutons pour deselectionner un jour deja choisi*/
+.OFF {
+    background-color: #AAFFAA;
+}
+
+div.nouveau_sondage a {
+    text-decoration: none;
+}
+div.nouveau_sondage span img {
+    vertical-align: middle;
+    border: 0px;
+}
+div.nouveau_sondage span {
+    margin-left: 20px;
+}
+
+div.error, div.addcomment {
+    text-align:center;
+    border: 1px;
+    font-family: arial;
+    font-size: 13px;
+}
+ul.exports {
+    text-align:center;
+    list-style-type : none ;
+}
+li.error {
+    color: red;
+}
+
+.half {
+    -moz-transform:scale(0.5);
+    -webkit-transform:scale(0.5);
+    transform:scale(0.5);
+}
diff --git a/htdocs/opensurvey/fonctions.php b/htdocs/opensurvey/fonctions.php
new file mode 100755
index 0000000000000000000000000000000000000000..9c3ecba0b2d0f92bc0ea84d398acab326dbb1ac1
--- /dev/null
+++ b/htdocs/opensurvey/fonctions.php
@@ -0,0 +1,293 @@
+<?php
+/* Copyright (C) 2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+* 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
+* (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ *	\file       htdocs/opensurvey/fonction.php
+ *	\ingroup    opensurvey
+ *	\brief      Functions for module
+ */
+
+
+
+/**
+ * Show header for new member
+ *
+ * @param 	string		$title				Title
+ * @param 	string		$head				Head array
+ * @param 	int    		$disablejs			More content into html header
+ * @param 	int    		$disablehead		More content into html header
+ * @param 	array  		$arrayofjs			Array of complementary js files
+ * @param 	array  		$arrayofcss			Array of complementary css files
+ * @return	void
+ */
+function llxHeaderSurvey($title, $head="", $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='')
+{
+	global $user, $conf, $langs, $mysoc;
+
+	top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers
+	print '<body id="mainbody" class="publicnewmemberform" style="margin-top: 10px;">';
+
+	showlogo();
+
+	print '<div style="margin-left: 50px; margin-right: 50px;">';
+}
+
+/**
+ * Show footer for new member
+ *
+ * @return	void
+ */
+function llxFooterSurvey()
+{
+	print '</div>';
+
+	printCommonFooter('public');
+
+	dol_htmloutput_events();
+
+	print "</body>\n";
+	print "</html>\n";
+}
+
+
+/**
+ * Show logo
+ *
+ * @return	void
+ */
+function showlogo()
+{
+	global $user, $conf, $langs, $mysoc;
+
+	// Print logo
+	$urllogo=DOL_URL_ROOT.'/theme/login_logo.png';
+
+	if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
+	{
+		$urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=companylogo&amp;file='.urlencode('thumbs/'.$mysoc->logo_small);
+	}
+	elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
+	{
+		$urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=companylogo&amp;file='.urlencode($mysoc->logo);
+		$width=128;
+	}
+	elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png'))
+	{
+		$urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
+	}
+	print '<center>';
+	print '<img alt="Logo" id="logosubscribe" title="" src="'.$urllogo.'" style="max-width: 120px" /><br>';
+	print '<strong>'.$langs->trans("OpenSurvey").'</strong>';
+	print '</center><br>';
+}
+
+
+/**
+ * get_server_name
+ *
+ * @return	string		URL to use
+ */
+function get_server_name()
+{
+	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+	$url=$urlwithouturlroot.dol_buildpath('/opensurvey/',1);
+
+	if (!preg_match("|/$|", $url)) {
+		$url = $url."/";
+	}
+
+	return $url;
+}
+
+
+/**
+ * is_error
+ *
+ * @param unknown_type $cerr error number
+ * @return 	boolean				Error key found or not
+ */
+function is_error($cerr)
+{
+	global $err;
+	if ( $err == 0 ) {
+		return false;
+	}
+
+	return (($err & $cerr) != 0 );
+}
+
+
+
+/**
+ * Vérifie une adresse e-mail selon les normes RFC
+ *
+ * @param  	string  $email  l'adresse e-mail a vérifier
+ * @return  bool    vrai si l'adresse est correcte, faux sinon
+ * @see 	http://fightingforalostcause.net/misc/2006/compare-email-regex.php
+ * @see 	http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c?view=markup
+ */
+function validateEmail($email)
+{
+	$pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
+
+	return (bool) preg_match($pattern, $email);
+}
+
+
+/**
+ * Fonction vérifiant l'existance et la valeur non vide d'une clé d'un tableau
+ *
+ * @param   string  $name       La clé à tester
+ * @param   array   $tableau    Le tableau où rechercher la clé ($_POST par défaut)
+ * @return  bool                Vrai si la clé existe et renvoie une valeur non vide
+ */
+function issetAndNoEmpty($name, $tableau = null)
+{
+	if ($tableau === null) {
+		$tableau = $_POST;
+	}
+
+	return (isset($tableau[$name]) === true && empty($tableau[$name]) === false);
+}
+
+
+/**
+ * Fonction permettant de générer les URL pour les sondage
+ *
+ * @param   string    $id     L'identifiant du sondage
+ * @param   bool      $admin  True pour générer une URL pour l'administration d'un sondage, False pour un URL publique
+ * @return  string            L'url pour le sondage
+ */
+function getUrlSondage($id, $admin = false)
+{
+	if ($admin === true) {
+		$url = get_server_name().'adminstuds_preview.php?sondage='.$id;
+	} else {
+		$url = get_server_name().'/public/studs.php?sondage='.$id;
+	}
+
+	return $url;
+}
+
+
+/**
+ * 	Generate a random id
+ *
+ *	@param	string	$car	Char to generate key
+ * 	@return	void
+ */
+function dol_survey_random($car)
+{
+	$string = "";
+	$chaine = "abcdefghijklmnopqrstuvwxyz123456789";
+	srand((double) microtime()*1000000);
+	for($i=0; $i<$car; $i++) {
+		$string .= $chaine[rand()%strlen($chaine)];
+	}
+	return $string;
+}
+
+/**
+ * Add a poll
+ *
+ * @param	string	$origin		Origin of poll creation
+ * @return	void
+ */
+function ajouter_sondage($origin)
+{
+	global $conf, $db;
+
+	$sondage=dol_survey_random(16);
+	$sondage_admin=$sondage.dol_survey_random(8);
+
+	if ($_SESSION["formatsondage"]=="A"||$_SESSION["formatsondage"]=="A+") {
+		//extraction de la date de fin choisie
+		if ($_SESSION["champdatefin"]) {
+			if ($_SESSION["champdatefin"]>time()+250000) {
+				$date_fin=$_SESSION["champdatefin"];
+			}
+		} else {
+			$date_fin=time()+15552000;
+		}
+	}
+
+	if ($_SESSION["formatsondage"]=="D"||$_SESSION["formatsondage"]=="D+") {
+		//Calcul de la date de fin du sondage
+		$taille_tableau=count($_SESSION["totalchoixjour"])-1;
+		$date_fin=$_SESSION["totalchoixjour"][$taille_tableau]+200000;
+	}
+
+	if (is_numeric($date_fin) === false) {
+		$date_fin = time()+15552000;
+	}
+	$canedit=empty($_SESSION['formatcanedit'])?'0':'1';
+
+	// Insert survey
+	$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_sondage';
+	$sql.= '(id_sondage, commentaires, mail_admin, nom_admin, titre, id_sondage_admin, date_fin, format, mailsonde, canedit, origin, sujet)';
+	$sql.= " VALUES ('".$db->escape($sondage)."', '".$db->escape($_SESSION['commentaires'])."', '".$db->escape($_SESSION['adresse'])."', '".$db->escape($_SESSION['nom'])."',";
+	$sql.= " '".$db->escape($_SESSION['titre'])."', '".$sondage_admin."', '".$db->idate($date_fin)."', '".$_SESSION['formatsondage']."', '".$db->escape($_SESSION['mailsonde'])."',";
+	$sql.= " '".$canedit."', '".$db->escape($origin)."',";
+	$sql.= " '".$db->escape($_SESSION['toutchoix'])."'";
+	$sql.= ")";
+	dol_syslog($sql);
+	$resql=$db->query($sql);
+
+	if ($origin == 'dolibarr') $urlback=dol_buildpath('/opensurvey/adminstuds_preview.php',1).'?sondage='.$sondage_admin;
+	else
+	{
+		// Define $urlwithroot
+		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+		$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/studs.php',1).'?sondage='.$sondage;
+
+		$urlback=$url;
+
+		//var_dump($urlback);exit;
+	}
+
+	unset($_SESSION["titre"]);
+	unset($_SESSION["nom"]);
+	unset($_SESSION["adresse"]);
+	unset($_SESSION["commentaires"]);
+	unset($_SESSION["canedit"]);
+	unset($_SESSION["mailsonde"]);
+
+	header("Location: ".$urlback);
+	exit();
+}
+
+
+
+define('COMMENT_EMPTY',         0x0000000001);
+define('COMMENT_USER_EMPTY',    0x0000000010);
+define('COMMENT_INSERT_FAILED', 0x0000000100);
+define('NAME_EMPTY',            0x0000001000);
+define('NAME_TAKEN',            0x0000010000);
+define('NO_POLL',               0x0000100000);
+define('NO_POLL_ID',            0x0001000000);
+define('INVALID_EMAIL',         0x0010000000);
+define('TITLE_EMPTY',           0x0100000000);
+define('INVALID_DATE',          0x1000000000);
+$err = 0;
+
+?>
diff --git a/htdocs/opensurvey/img/accept-24.png b/htdocs/opensurvey/img/accept-24.png
new file mode 100755
index 0000000000000000000000000000000000000000..65ca043ee12627bd42bb6e8563fb73ed61e07d06
Binary files /dev/null and b/htdocs/opensurvey/img/accept-24.png differ
diff --git a/htdocs/opensurvey/img/accept-32.png b/htdocs/opensurvey/img/accept-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..c94c066edee91b802be27455483a21113fd1c1eb
Binary files /dev/null and b/htdocs/opensurvey/img/accept-32.png differ
diff --git a/htdocs/opensurvey/img/accept.png b/htdocs/opensurvey/img/accept.png
new file mode 100755
index 0000000000000000000000000000000000000000..ada57a9ae60ebccf4cf8f4fcb9523cffbc6c51d0
Binary files /dev/null and b/htdocs/opensurvey/img/accept.png differ
diff --git a/htdocs/opensurvey/img/add-16.png b/htdocs/opensurvey/img/add-16.png
new file mode 100755
index 0000000000000000000000000000000000000000..23d5bed776023cee0402e7c0b1649d57704e36d3
Binary files /dev/null and b/htdocs/opensurvey/img/add-16.png differ
diff --git a/htdocs/opensurvey/img/add-24.png b/htdocs/opensurvey/img/add-24.png
new file mode 100755
index 0000000000000000000000000000000000000000..c63af7f39062ad0d5b9f1c5f9afa617e7ada0d5d
Binary files /dev/null and b/htdocs/opensurvey/img/add-24.png differ
diff --git a/htdocs/opensurvey/img/add.png b/htdocs/opensurvey/img/add.png
new file mode 100755
index 0000000000000000000000000000000000000000..7409ef332d2435c3fb43c879a80c9fcb5820f796
Binary files /dev/null and b/htdocs/opensurvey/img/add.png differ
diff --git a/htdocs/opensurvey/img/back-32.png b/htdocs/opensurvey/img/back-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..b44fbb2385acd6ba9eec5f4c00e47cc5518b23dc
Binary files /dev/null and b/htdocs/opensurvey/img/back-32.png differ
diff --git a/htdocs/opensurvey/img/calendar-32.png b/htdocs/opensurvey/img/calendar-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..89761150635adaf8ef0434c9fcb1175ccc0aad04
Binary files /dev/null and b/htdocs/opensurvey/img/calendar-32.png differ
diff --git a/htdocs/opensurvey/img/cancel.png b/htdocs/opensurvey/img/cancel.png
new file mode 100755
index 0000000000000000000000000000000000000000..c149c2bc017d5ce5a8ae9330dd7dbd012482e0f4
Binary files /dev/null and b/htdocs/opensurvey/img/cancel.png differ
diff --git a/htdocs/opensurvey/img/chart-32.png b/htdocs/opensurvey/img/chart-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..1406b8da933f7ee21f09bf55ce4e81ce3312e54f
Binary files /dev/null and b/htdocs/opensurvey/img/chart-32.png differ
diff --git a/htdocs/opensurvey/img/csv.png b/htdocs/opensurvey/img/csv.png
new file mode 100755
index 0000000000000000000000000000000000000000..f90ef25ec7f1cb0fdae38d9fe2d9edeee9928ef1
Binary files /dev/null and b/htdocs/opensurvey/img/csv.png differ
diff --git a/htdocs/opensurvey/img/fforward.png b/htdocs/opensurvey/img/fforward.png
new file mode 100755
index 0000000000000000000000000000000000000000..369084cdf149b47c66e5ef6dc31a21876f3feb40
Binary files /dev/null and b/htdocs/opensurvey/img/fforward.png differ
diff --git a/htdocs/opensurvey/img/ical.png b/htdocs/opensurvey/img/ical.png
new file mode 100755
index 0000000000000000000000000000000000000000..b092a75b6da3e338621c548c4620c143df9f5cc6
Binary files /dev/null and b/htdocs/opensurvey/img/ical.png differ
diff --git a/htdocs/opensurvey/img/info.png b/htdocs/opensurvey/img/info.png
new file mode 100755
index 0000000000000000000000000000000000000000..4c665a4f0a10633d475480553f673bceb10f594a
Binary files /dev/null and b/htdocs/opensurvey/img/info.png differ
diff --git a/htdocs/opensurvey/img/medaille.png b/htdocs/opensurvey/img/medaille.png
new file mode 100755
index 0000000000000000000000000000000000000000..97a22b72eea2e8d65655993c68a9e03f6a40aa9e
Binary files /dev/null and b/htdocs/opensurvey/img/medaille.png differ
diff --git a/htdocs/opensurvey/img/next-32.png b/htdocs/opensurvey/img/next-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..934a254f307b0d140219e13c723a4fc6836ed881
Binary files /dev/null and b/htdocs/opensurvey/img/next-32.png differ
diff --git a/htdocs/opensurvey/img/next.png b/htdocs/opensurvey/img/next.png
new file mode 100755
index 0000000000000000000000000000000000000000..24d94e830a33157c791a714ab60565f9aebf0d6e
Binary files /dev/null and b/htdocs/opensurvey/img/next.png differ
diff --git a/htdocs/opensurvey/img/object_opensurvey.png b/htdocs/opensurvey/img/object_opensurvey.png
new file mode 100755
index 0000000000000000000000000000000000000000..042d82172576c5653ed257e778eb73fa1ddfefda
Binary files /dev/null and b/htdocs/opensurvey/img/object_opensurvey.png differ
diff --git a/htdocs/opensurvey/img/opensurvey.png b/htdocs/opensurvey/img/opensurvey.png
new file mode 100644
index 0000000000000000000000000000000000000000..d8975acc1ae727aee541a51eb5b2218e1c5707ee
Binary files /dev/null and b/htdocs/opensurvey/img/opensurvey.png differ
diff --git a/htdocs/opensurvey/img/opensurvey_logo.png b/htdocs/opensurvey/img/opensurvey_logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..eb266ae05cf56559595b9580f33aeb9f4c4fced1
Binary files /dev/null and b/htdocs/opensurvey/img/opensurvey_logo.png differ
diff --git a/htdocs/opensurvey/img/previous.png b/htdocs/opensurvey/img/previous.png
new file mode 100755
index 0000000000000000000000000000000000000000..b4b79aeec517f11788920581a3b6044a2bf80930
Binary files /dev/null and b/htdocs/opensurvey/img/previous.png differ
diff --git a/htdocs/opensurvey/img/reload.png b/htdocs/opensurvey/img/reload.png
new file mode 100755
index 0000000000000000000000000000000000000000..9a2b2e82d365739d12d026dba599afa059bf2486
Binary files /dev/null and b/htdocs/opensurvey/img/reload.png differ
diff --git a/htdocs/opensurvey/img/rewind.png b/htdocs/opensurvey/img/rewind.png
new file mode 100755
index 0000000000000000000000000000000000000000..99ed78c3c915ee96c26064aa45e8adc235f6c63e
Binary files /dev/null and b/htdocs/opensurvey/img/rewind.png differ
diff --git a/htdocs/opensurvey/index.php b/htdocs/opensurvey/index.php
new file mode 100755
index 0000000000000000000000000000000000000000..21babf4f2e8b8f1ed38da85cb6455622ba438c21
--- /dev/null
+++ b/htdocs/opensurvey/index.php
@@ -0,0 +1,69 @@
+<?php
+/* Copyright (C) 2013 Laurent Destailleur  <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/index.php
+ *	\ingroup    opensurvey
+ *	\brief      Home page of opensurvey area
+ */
+
+require_once('../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+
+
+
+/*
+ * View
+ */
+
+$langs->load("opensurvey@opensurvey");
+llxHeader();
+
+$nbsondages=0;
+$sql='SELECT COUNT(*) as nb FROM '.MAIN_DB_PREFIX.'opensurvey_sondage';
+$resql=$db->query($sql);
+if ($resql)
+{
+	$obj=$db->fetch_object($resql);
+	$nbsondages=$obj->nb;
+}
+else dol_print_error($db,'');
+
+print_fiche_titre($langs->trans("OpenSurveyArea"));
+
+echo $langs->trans("NoSurveysInDatabase",$nbsondages).'<br><br>'."\n";
+
+
+// Link
+print img_picto('','object_globe.png').' '.$langs->trans("PublicLinkToCreateSurvey").':<br>';
+
+// Define $urlwithroot
+$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/index.php',1);
+$urllink='<a href="'.$url.'" target="_blank">'.$url.'</a>';
+print $urllink;
+
+
+
+llxFooter();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/langs/en_US/opensurvey.lang b/htdocs/opensurvey/langs/en_US/opensurvey.lang
new file mode 100755
index 0000000000000000000000000000000000000000..8ab490212599e75faf4c4e4367678aa5d0f3f019
--- /dev/null
+++ b/htdocs/opensurvey/langs/en_US/opensurvey.lang
@@ -0,0 +1,68 @@
+# Dolibarr language file - en_US - opensurvey
+CHARSET=UTF-8
+Survey=Survey
+Surveys=Surveys
+OrganizeYourMeetingEasily=Organize your meeting and surveys easily. First select type of survey...
+NewSurvey=New survey
+NoSurveysInDatabase=%s survey(s) into database.
+OpenSurveyArea=Surveys area
+AddACommentForPoll=You can add a comment into survey...
+AddComment=Add comment
+CreatePoll=Create poll
+PollTitle=Poll title
+OpenSurveyYourName=Your name
+OpenSurveyYourEMail=Your email address
+VotersCanModify=Voters can modify vote of others
+ToReceiveEMailForEachVote=To receive an email for each vote
+TypeDate=Type date
+TypeClassic=Type standard
+YouAreInPollCreateArea=You are in the poll creation section
+FieldMandatory=Field mandatory
+OpenSurveyDesc=Online service to plan a rendez-vous or do a survey quickly and easily.
+OpenSurveyNoRegistration=No registration required.
+OpenSurveyStep2=Select your dates amoung the free days (green). The selected days are in blue. You can unselect a day previously selected by clicking again on it
+RemoveAllDays=Remove all days
+CopyHoursOfFirstDay=Copy hours of first day
+RemoveAllHours=Remove all hours
+SelectedDays=Selected days
+TheBestChoice=The best choice currently is
+TheBestChoices=The best choices currently are
+with=with
+OpenSurveyHowTo=If you agree to vote in this poll, you have to give your name, choose the values that fit best for you (without paying attention to the choices of the other voters) and validate with the plus button at the end of the line. 
+InitiatorOfPoll=Initiator of the poll
+CommentsOfVoters=Comments of voters
+ConfirmRemovalOfPoll=Are you sure you want to remove this poll (and all votes)
+RemovePoll=Remove poll
+PollManagement=Poll's management
+BackToHoursSetup=Back to hours setup
+UrlForSurvey=URL to communicate to get a direct access to survey
+PollOnChoice=Your are creating a poll to make a multi-choice for a poll. First enter all possible choices for your poll:
+CheckBox=Simple checkbox
+YesNoList=List (empty/yes/no)
+PourContreList=List (empty/for/against)
+AddNewColumn=Add new colum
+TitleChoice=Choice label
+InfoAfterCreate=Once you have confirmed the creation of your poll, you will be automatically redirected on the page of your poll.<br>You should also receive an email with link to your poll for sending it to the voters.
+ExportSpreadsheet=Export result spreadsheet
+ExpireDate=Limit date
+NbOfVoters=Nb of voters
+SurveyResults=Results
+PollAdminDesc=You are allowed to change all vote lines of this poll with button "Edit". You can, as well, remove a column or a line with %s. You can also add a new column with %s.
+5MoreChoices=5 more choices
+Abstention=Abstention
+Against=Against
+YouAreInivitedToVote=You are invited to vote for this poll
+VoteNameAlreadyExists=This name was already used for this poll
+ErrorPollDoesNotExists=Error, poll <strong>%s</strong> does not exists.
+OpenSurveyNothingToSetup=There is no specific setup to do.
+PollWillExpire=Your poll will expire automatically <strong>%s</strong> days after the last date of your poll.
+RemovalDate=Removal date
+AddADate=Add a date
+AddStartHour=Add start hour
+AddEndHour=Add end hour
+votes=vote(s)
+NoCommentYet=No comment yet posted for this poll
+CanEditVotes=Can change vote of others
+SelectDayDesc=For each selected day, you can choose, or not, meeting hours in the following format :<br>- empty,<br>- "8h", "8H" or "8:00" to give a meeting's start hour,<br>- "8-11", "8h-11h", "8H-11H" or "8:00-11:00" to give a meeting's start and end hour,<br>- "8h15-11h15", "8H15-11H15" or "8:15-11:15" for the same thing but with minutes.
+BackToCurrentMonth=Back to current month
+PublicLinkToCreateSurvey=Public link to allow everybody to create a survey
\ No newline at end of file
diff --git a/htdocs/opensurvey/langs/fr_FR/opensurvey.lang b/htdocs/opensurvey/langs/fr_FR/opensurvey.lang
new file mode 100755
index 0000000000000000000000000000000000000000..12fc74f258d8235f95a61b0934f2b9682e12bbda
--- /dev/null
+++ b/htdocs/opensurvey/langs/fr_FR/opensurvey.lang
@@ -0,0 +1,68 @@
+# Dolibarr language file - fr_FR - opensurvey
+CHARSET=UTF-8
+Survey=Sondage
+Surveys=Sondages
+OrganizeYourMeetingEasily=Organiser vos rendez-vous ou votes facilement, librement. Sélectionnez d'abord le type de sondage...
+NewSurvey=Nouveau sondage
+NoSurveysInDatabase=%s sondage(s) en base.
+OpenSurveyArea=Espace sondage
+AddACommentForPoll=Vous pouvez ajouter un commentaire au sondage...
+AddComment=Ajouter commentaire
+CreatePoll=Créer sondage
+PollTitle=Titre sondage
+OpenSurveyYourName=Votre nom
+OpenSurveyYourEMail=Votre adresse email
+VotersCanModify=Les votants peuvent modifier les votes des autres
+ToReceiveEMailForEachVote=Pour recevoir un email à chaque vote
+TypeDate=Type date
+TypeClassic=Type classique
+YouAreInPollCreateArea=Vous êtes dans l'espace de création de sondage
+FieldMandatory=Champ obligatoire
+OpenSurveyDesc=Service en ligne permettant de planifier un rendez-vous ou réaliser un sondage rapidement et simplement.
+OpenSurveyNoRegistration=Aucune inscription préalable n'est nécessaire.
+OpenSurveyStep2=Sélectionner les dates parmis les jours libres (en vert). Les jours sélectionné sont bleus. Vou spouvez désélectionner un jour en cliquant à nouveau dessus.
+RemoveAllDays=Efface tous les jours
+CopyHoursOfFirstDay=Copier heures du premier jour
+RemoveAllHours=Efface toutes les heures
+SelectedDays=Jours sélectionnés
+TheBestChoice=Le meilleur choix actuellement est
+TheBestChoices=Les meilleurs choix actuellement sont
+with=avec
+OpenSurveyHowTo=Si vous acceptez de voter pour ce sondage, vous devez saisir votre nom, choisir les valeurs qui correspondent à votre choix (sans prêter attention aux choix des autres déjà saisis) et valider en cliquant sur le bouton + à la fin de la ligne.
+InitiatorOfPoll=Initiateur du sondage
+CommentsOfVoters=Commentaires des votants
+ConfirmRemovalOfPoll=Etes vous sur de vouloir supprimer ce sondage (et tous ces votes) 
+RemovePoll=Suppression du sondage 
+PollManagement=Gestion du sondage
+BackToHoursSetup=Retour configuration heures
+UrlForSurvey=URL à communiquer pour accès direct au sondage
+PollOnChoice=Vous êtes en train de créer un sondage à choix multiples. Renseigner les différents choix possible de votre sondage:
+CheckBox=Case à cochée
+YesNoList=Liste (vide/oui/non)
+PourContreList=Liste (vide/pour/contre)
+AddNewColumn=Ajouter nouvelle colonne
+TitleChoice=Libellé du choix
+InfoAfterCreate=Une fois la confirmation de la création de votre sondage réalisée, vous serez redirigé vers la page de vote du sondage.<br>Vous devriez de plus recevoir un email avec le lien de la page sondage pour diffusion auprès des votants.
+ExportSpreadsheet=Exporter feuille de résultats
+ExpireDate=Date expiration
+NbOfVoters=Nb de votants
+SurveyResults=Résultats
+PollAdminDesc=Vous êtes habilités à modifier toutes les lignes de votes par le bouton "Editer". Vous pouvez supprimer une colonne ou ligne avec %s. Vous pouvez aussi ajouter une nouvelle colonne avec %s.
+5MoreChoices=5 choix suplémentaires
+Abstention=Abstention
+Against=Contre
+YouAreInivitedToVote=Vous êtes invité à vous prononcer sur ce vote/sondage
+VoteNameAlreadyExists=Ce nom a déjà été utilisé pour ce vote
+ErrorPollDoesNotExists=Erreur, le sondage <strong>%s</strong> n'existe pas.
+OpenSurveyNothingToSetup=Aucune configuration particulière n'est requise.
+PollWillExpire=Ce sondage expirera automatiquement <strong>%s</strong> jours après la date de dernier choix.
+Removal date=Date d'expiration
+AddADate=Ajouter une date
+AddStartHour=Ajouter heure de début
+AddEndHour=Ajouter heure de fin
+votes=vote(s)
+NoCommentYet=Pas de commentaires laissés pour le moment sur ce sondage
+CanEditVotes=Modification des votes des autres autorisés
+SelectDayDesc=Pour chaque jour, vous pouvez choisir, ou pas, les heures au format suivant :<br>- laisser vide,<br>- "8h", "8H" ou "8:00" pour définir uniquement une heure de début,<br>- "8-11", "8h-11h", "8H-11H" ou "8:00-11:00" pour définir une heure de début et de fin,<br>- "8h15-11h15", "8H15-11H15" ou "8:15-11:15" pour définir une heure de début et fin avec précision sur les minutes.
+BackToCurrentMonth=Retour au mois en cours
+PublicLinkToCreateSurvey=Lien publique pour permettre à tout le monde de créer un sondage
diff --git a/htdocs/opensurvey/list.php b/htdocs/opensurvey/list.php
new file mode 100755
index 0000000000000000000000000000000000000000..20a3ed50d94865424b94f80d32c6c4289f1c2bfb
--- /dev/null
+++ b/htdocs/opensurvey/list.php
@@ -0,0 +1,145 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/list.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to list surveys
+ */
+
+require_once('../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+
+$action=GETPOST('action');
+$id=GETPOST('id');
+
+if (! $sortorder) $sortorder="ASC";
+if (! $sortfield) $sortfield="p.titre";
+if ($page < 0) {
+	$page = 0;
+}
+$limit = $conf->liste_limit;
+$offset = $limit * $page;
+
+
+/*
+ * Actions
+ */
+
+if ($action == 'delete_confirm')
+{
+	$db->begin();
+
+	$sql='DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage_admin = '".$id."'";
+	dol_syslog("Delete poll sql=".$sql, LOG_DEBUG);
+	$resql=$db->query($sql);
+	$sql='DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage_admin = '".$id."'";
+	dol_syslog("Delete poll sql=".$sql, LOG_DEBUG);
+	$resql=$db->query($sql);
+	$sql='DELETE FROM '.MAIN_DB_PREFIX."opensurvey_sondage WHERE id_sondage_admin = '".$id."'";
+	dol_syslog("Delete poll sql=".$sql, LOG_DEBUG);
+	$resql=$db->query($sql);
+
+	$db->commit();
+}
+
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+
+$langs->load("opensurvey@opensurvey");
+llxHeader();
+
+print '<div class=corps>'."\n";
+
+print_fiche_titre($langs->trans("OpenSurveyArea"));
+
+
+if ($action == 'delete')
+{
+	print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$id, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll",$id), 'delete_confirm', '', '', 1);
+}
+
+
+// tableau qui affiche tous les sondages de la base
+print '<table class="liste">'."\n";
+print '<tr class="liste_titre"><td>'. $langs->trans("Survey").'</td><td>'. $langs->trans("Type") .'</td><td>'. $langs->trans("Title") .'</td><td>'. $langs->trans("Author") .'</td><td align="center">'. $langs->trans("ExpireDate") .'</td><td align="center">'. $langs->trans("NbOfVoters") .'</td><td colspan=2>&nbsp;</td>'."\n";
+
+$sql = "SELECT id_sondage, id_sondage_admin, mail_admin, format, origin, date_fin, titre, nom_admin";
+$sql.= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p";
+// Count total nb of records
+$nbtotalofrecords = 0;
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
+{
+	$result = $db->query($sql);
+	$nbtotalofrecords = $db->num_rows($result);
+}
+$sql.= " ORDER BY $sortfield $sortorder ";
+$sql.= " ".$db->plimit($conf->liste_limit+1, $offset);
+
+$resql=$db->query($sql);
+if (! $resql) dol_print_error($db);
+
+$num=$db->num_rows($resql);
+
+$i = 0; $var = true;
+while ($i < min($num,$limit))
+{
+	$obj=$db->fetch_object($resql);
+
+	$sql2='select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->id_sondage)."'";
+	$resql2=$db->query($sql2);
+	if ($resql2)
+	{
+		$obj2=$db->fetch_object($resql2);
+		$nbuser=$obj2->nb;
+	}
+	else dol_print_error($db);
+
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>';
+	print '<a href="'.dol_buildpath('/opensurvey/adminstuds.php',1).'?sondage='.$obj->id_sondage_admin.'">'.img_picto('','object_opensurvey@opensurvey').' '.$obj->id_sondage.'</a>';
+	print '</td><td>';
+	$type=($obj->format=='A' || $obj->format=='A+')?'classic':'date';
+	print img_picto('',dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'),1),'width="16"',1);
+	print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate");
+	print '</td><td>'.$obj->titre.'</td><td>'.$obj->nom_admin.'</td>';
+
+	print '<td align="center">'.dol_print_date($db->jdate($obj->date_fin),'day');
+	if ($db->jdate($obj->date_fin) < time()) { print ' '.img_warning(); }
+	print '</td>';
+
+	print'<td align="center">'.$nbuser.'</td>'."\n";
+	print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?id='.$obj->id_sondage_admin.'&action=delete">'.img_picto('', 'delete.png').'</a></td>'."\n";
+
+	print '</tr>'."\n";
+	$i++;
+}
+
+print '</table>'."\n";
+print '</div>'."\n";
+
+llxFooter();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/public/choix_autre.php b/htdocs/opensurvey/public/choix_autre.php
new file mode 100755
index 0000000000000000000000000000000000000000..5975f9d4a0c2d536e77c4e761bfbc28cb42493d1
--- /dev/null
+++ b/htdocs/opensurvey/public/choix_autre.php
@@ -0,0 +1,222 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/public/choix_autre.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to create a new survey (choice selection)
+ */
+
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+$erreur = false;
+$testdate = true;
+$date_selected = '';
+
+$origin=GETPOST('origin','alpha');
+
+
+
+/*
+ * Action
+ */
+
+// Set session vars
+$erreur_injection = false;
+if (isset($_SESSION["nbrecases"])) {
+	for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) {
+		if (isset($_POST["choix"][$i])) {
+			$_SESSION["choix$i"]=$_POST["choix"][$i];
+		}
+		if (isset($_POST["typecolonne"][$i])) {
+			$_SESSION["typecolonne$i"]=$_POST["typecolonne"][$i];
+		}
+	}
+} else { //nombre de cases par défaut
+	$_SESSION["nbrecases"]=5;
+}
+
+if (isset($_POST["ajoutcases"]) || isset($_POST["ajoutcases_x"])) {
+	$_SESSION["nbrecases"]=$_SESSION["nbrecases"]+5;
+}
+
+// Create survey into database
+if (isset($_POST["confirmecreation"]) || isset($_POST["confirmecreation_x"]))
+{
+	//recuperation des données de champs textes
+	$toutchoix = '';
+	for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++)
+	{
+		if (! empty($_POST["choix"][$i]))
+		{
+			$toutchoix.=',';
+			$toutchoix.=str_replace(array(",","@"), " ", $_POST["choix"][$i]).(empty($_POST["typecolonne"][$i])?'':'@'.$_POST["typecolonne"][$i]);
+		}
+	}
+
+	$toutchoix=substr("$toutchoix",1);
+	$_SESSION["toutchoix"]=$toutchoix;
+
+	if (GETPOST('champdatefin'))
+	{
+		$registredate=explode("/",$_POST["champdatefin"]);
+		if (is_array($registredate) === false || count($registredate) !== 3) {
+			$testdate = false;
+			$date_selected = $_POST["champdatefin"];
+		} else {
+			$time = mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]);
+			if ($time === false || date('d/m/Y', $time) !== $_POST["champdatefin"]) {
+				$testdate = false;
+				$date_selected = $_POST["champdatefin"];
+			} else {
+				if (mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]) > time() + 250000) {
+					$_SESSION["champdatefin"]=mktime(0,0,0,$registredate[1],$registredate[0],$registredate[2]);
+				}
+			}
+		}
+	} else {
+		$_SESSION["champdatefin"]=time()+15552000;
+	}
+
+	if ($testdate === true)
+	{
+		//format du sondage AUTRE
+		$_SESSION["formatsondage"]="A";
+		$_SESSION["caneditsondage"]=$_SESSION["canedit"];
+
+		// Add into database
+		ajouter_sondage($origin);
+	} else {
+		$_POST["fin_sondage_autre"] = 'ok';
+	}
+}
+
+
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeaderSurvey($langs->trans("OpenSurvey"), "", 0, 0, $arrayofjs, $arrayofcss);
+
+if (empty($_SESSION['titre']) || empty($_SESSION['nom']) || empty($_SESSION['adresse']))
+{
+	dol_print_error('',"You haven't filled the first section of the poll creation");
+	llxFooterSurvey();
+	exit;
+}
+
+
+//partie creation du sondage dans la base SQL
+//On prépare les données pour les inserer dans la base
+
+print '<form name="formulaire" action="#bas" method="POST" onkeypress="javascript:process_keypress(event)">'."\n";
+print '<input type="hidden" name="origin" value="'.dol_escape_htmltag($origin).'">';
+
+print '<div class="bandeautitre">'. $langs->trans("CreatePoll")." (2 / 2)" .'</div>'."\n";
+
+print '<div class=corps>'."\n";
+print '<br>'. $langs->trans("PollOnChoice") .'<br><br>'."\n";
+print '<table>'."\n";
+
+//affichage des cases texte de formulaire
+for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) {
+	$j = $i + 1;
+	if (isset($_SESSION["choix$i"]) === false) {
+		$_SESSION["choix$i"] = '';
+	}
+	print '<tr><td>'. $langs->trans("TitleChoice") .' '.$j.' : </td><td><input type="text" name="choix[]" size="40" maxlength="40" value="'.dol_escape_htmltag($_SESSION["choix$i"]).'" id="choix'.$i.'">';
+	$tmparray=array('checkbox'=>$langs->trans("CheckBox"),'yesno'=>$langs->trans("YesNoList"),'foragainst'=>$langs->trans("PourContreList"));
+	print ' &nbsp; '.$langs->trans("Type").' '.$form->selectarray("typecolonne[]", $tmparray, $_SESSION["typecolonne$i"]);
+	print '</td></tr>'."\n";
+}
+
+print '</table>'."\n";
+
+//ajout de cases supplementaires
+print '<table><tr>'."\n";
+print '<td>'. $langs->trans("5MoreChoices") .'</td><td><input type="image" name="ajoutcases" value="Retour" src="images/add-16.png"></td>'."\n";
+print '</tr></table>'."\n";
+print'<br>'."\n";
+
+print '<table><tr>'."\n";
+print '<td></td><td><input type="submit" class="button" name="fin_sondage_autre" value="'.dol_escape_htmltag($langs->trans("NextStep")).'" src="images/next-32.png"></td>'."\n";
+print '</tr></table>'."\n";
+
+//test de remplissage des cases
+$testremplissage = '';
+for ($i=0;$i<$_SESSION["nbrecases"];$i++)
+{
+	if (isset($_POST["choix"][$i]))
+	{
+		$testremplissage="ok";
+	}
+}
+
+//message d'erreur si aucun champ renseigné
+if ($testremplissage != "ok" && (isset($_POST["fin_sondage_autre"]) || isset($_POST["fin_sondage_autre_x"]))) {
+	print "<br><font color=\"#FF0000\">" . $langs->trans("Enter at least one choice") . "</font><br><br>"."\n";
+	$erreur = true;
+}
+
+//message d'erreur si mauvaise date
+if ($testdate === false) {
+	print "<br><font color=\"#FF0000\">" . _("Date must be have the format DD/MM/YYYY") . "</font><br><br>"."\n";
+}
+
+if ($erreur_injection) {
+	print "<font color=#FF0000>" . _("Characters \" < and > are not permitted") . "</font><br><br>\n";
+}
+
+if ((isset($_POST["fin_sondage_autre"]) || isset($_POST["fin_sondage_autre_x"])) && !$erreur && !$erreur_injection) {
+	//demande de la date de fin du sondage
+	print '<br>'."\n";
+	print '<div class=presentationdatefin>'."\n";
+	print '<br>'. _("Your poll will be automatically removed after 6 months.<br> You can fix another removal date for it.") .'<br><br>'."\n";
+	print _("Removal date (optional)") .' : <input type="text" name="champdatefin" value="'.$date_selected.'" size="10" maxlength="10"> '. _("(DD/MM/YYYY)") ."\n";
+	print '</div>'."\n";
+	print '<div class=presentationdatefin>'."\n";
+	print '<font color=#FF0000>'. $langs->trans("InfoAfterCreate") .'</font>'."\n";
+	print '</div>'."\n";
+	print '<br>'."\n";
+	print '<table>'."\n";
+	print '<tr><td>'. $langs->trans("CreatePoll") .'</td><td><input type="image" name="confirmecreation" src="images/add.png"></td></tr>'."\n";
+	print '</table>'."\n";
+}
+
+//fin du formulaire et bandeau de pied
+print '</form>'."\n";
+
+
+print '<a name=bas></a>'."\n";
+print '<br><br><br>'."\n";
+print '</div>'."\n";
+
+llxFooterSurvey();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/public/choix_date.php b/htdocs/opensurvey/public/choix_date.php
new file mode 100755
index 0000000000000000000000000000000000000000..59536f1f8e67c7ea5afae415b6c78848e157b0bc
--- /dev/null
+++ b/htdocs/opensurvey/public/choix_date.php
@@ -0,0 +1,573 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/public/choix_date.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to create a new survey (date selection)
+ */
+
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+$origin=GETPOST('origin','alpha');
+
+
+/*
+ * Actions
+ */
+
+// Insert survey
+if (GETPOST('confirmation') || GETPOST('confirmation_x'))
+{
+	if (is_array($_SESSION['totalchoixjour']))
+	{
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			if ($_SESSION["horaires$i"][0] == "" && $_SESSION["horaires$i"][1] == "" && $_SESSION["horaires$i"][2] == "" && $_SESSION["horaires$i"][3] == "" && $_SESSION["horaires$i"][4] == "") {
+				$choixdate.=",";
+				$choixdate .= $_SESSION["totalchoixjour"][$i];
+			} else {
+				for ($j=0;$j<$_SESSION["nbrecaseshoraires"];$j++) {
+					if ($_SESSION["horaires$i"][$j]!="") {
+						$choixdate.=",";
+						$choixdate .= $_SESSION["totalchoixjour"][$i];
+						$choixdate.="@";
+						// On remplace la virgule et l'arobase pour ne pas avoir de problème par la suite
+						$choixdate .= str_replace(array(',', '@'), array('&#44;', '&#64;'), $_SESSION["horaires$i"][$j]);
+					}
+				}
+			}
+		}
+	}
+	else dol_print_error('','array not defined');
+
+	$_SESSION["toutchoix"]=substr("$choixdate",1);
+	ajouter_sondage($origin);
+}
+
+// Reset days
+if (GETPOST('reset')) {
+	for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+		for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+			unset($_SESSION["horaires$i"][$j]);
+		}
+	}
+
+	unset($_SESSION["totalchoixjour"]);
+	unset($_SESSION["nbrecaseshoraires"]);
+}
+
+
+
+/*
+ * View
+ */
+
+if (! isset($_SESSION['nom']) && ! isset($_SESSION['adresse']) && ! isset($_SESSION['commentaires']) && ! isset($_SESSION['mail']))
+{
+	dol_print_error('',"You haven't filled the first section of the poll creation");
+	exit;
+}
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeaderSurvey($langs->trans("OpenSurvey"), "", 0, 0, $arrayofjs, $arrayofcss);
+
+//nombre de cases par défaut
+if (! isset($_SESSION["nbrecaseshoraires"]))
+{
+	$_SESSION["nbrecaseshoraires"]=5;
+}
+elseif ((GETPOST('ajoutcases') || GETPOST('ajoutcases_x')) && $_SESSION["nbrecaseshoraires"] == 5)
+{
+	$_SESSION["nbrecaseshoraires"]=10;
+}
+
+//valeurs de la date du jour actuel
+$jourAJ=date("j");
+$moisAJ=date("n");
+$anneeAJ=date("Y");
+
+// Initialisation des jour, mois et année
+if (! isset($_SESSION['jour'])) $_SESSION['jour']= date('j');
+if (! isset($_SESSION['mois'])) $_SESSION['mois']= date('n');
+if (! isset($_SESSION['annee'])) $_SESSION['annee']= date('Y');
+
+//mise a jour des valeurs de session si bouton retour a aujourd'hui
+if ((!issetAndNoEmpty('anneeavant_x') && !issetAndNoEmpty('anneeapres_x') && !issetAndNoEmpty('moisavant_x') && !issetAndNoEmpty('moisapres_x') && !issetAndNoEmpty('choixjourajout')) && !issetAndNoEmpty('choixjourretrait') || (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))){
+	$_SESSION["jour"]=date("j");
+	$_SESSION["mois"]=date("n");
+	$_SESSION["annee"]=date("Y");
+}
+
+//mise a jour des valeurs de session si mois avant
+if (issetAndNoEmpty('moisavant') || issetAndNoEmpty('moisavant_x')) {
+	if ($_SESSION["mois"] == 1) {
+		$_SESSION["mois"]   = 12;
+		$_SESSION["annee"]  = $_SESSION["annee"]-1;
+	} else {
+		$_SESSION["mois"] -= 1;
+	}
+
+	//On sauvegarde les heures deja entrées
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+			}
+		}
+	}
+}
+
+//mise a jour des valeurs de session si mois apres
+if (issetAndNoEmpty('moisapres') || issetAndNoEmpty('moisapres_x')) {
+	if ($_SESSION["mois"] == 12) {
+		$_SESSION["mois"] = 1;
+		$_SESSION["annee"] += 1;
+	} else {
+		$_SESSION["mois"] += 1;
+	}
+
+	//On sauvegarde les heures deja entrées
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+			}
+		}
+	}
+}
+
+//mise a jour des valeurs de session si annee avant
+if (issetAndNoEmpty('anneeavant') || issetAndNoEmpty('anneeavant_x')) {
+	$_SESSION["annee"] -= 1;
+
+	//On sauvegarde les heures deja entrées
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+			}
+		}
+	}
+}
+
+//mise a jour des valeurs de session si annee apres
+if (issetAndNoEmpty('anneeapres') || issetAndNoEmpty('anneeapres_x')) {
+	$_SESSION["annee"] += 1;
+
+	//On sauvegarde les heures deja entrées
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0;$j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+			}
+		}
+	}
+}
+
+//valeurs du nombre de jour dans le mois et du premier jour du mois
+$nbrejourmois = date("t", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"]));
+$premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1;
+
+//le format du sondage est DATE
+$_SESSION["formatsondage"] = "D";
+$_SESSION["formatcanedit"] = $_SESSION["canedit"];
+
+//traduction de la valeur du mois
+if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13)
+{
+	$motmois=dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B');
+}
+else
+{
+	$motmois=dol_print_date(dol_now(), '%B');
+}
+
+
+//Debut du formulaire et bandeaux de tete
+print '<form name="formulaire" action="choix_date.php" method="POST" onkeypress="javascript:process_keypress(event)">'."\n";
+print '<input type="hidden" name="origin" value="'.dol_escape_htmltag($origin).'">';
+
+print '<div class="bandeautitre">'. $langs->trans("CreatePoll")." (2 / 2)" .'</div>'."\n";
+
+//affichage de l'aide pour les jours
+print '<div class="bodydate">'."\n";
+print $langs->trans("OpenSurveyStep2")."\n";
+print '</div>'."\n";
+
+//debut du tableau qui affiche le calendrier
+print '<center><div class="corps">'."\n";
+print '<table align=center>'."\n";
+print '<tr><td><input type="image" name="anneeavant" value="<<" src="images/rewind.png"></td><td><input type="image" name="moisavant" value="<" src="images/previous.png"></td>';
+print '<td width="150px" align="center"> '.$motmois.' '.$_SESSION["annee"].'<br>';
+print '<input type="image" name="retourmois" alt="'.dol_escape_htmltag($langs->trans("BackToCurrentMonth")).'" title="'.dol_escape_htmltag($langs->trans("BackToCurrentMonth")).'" value="" src="'.img_picto('', 'refresh','',0,1).'">';
+print '</td><td><input type="image" name="moisapres" value=">" src="images/next.png"></td>';
+print '<td><input type="image" name="anneeapres" value=">>" src="images/fforward.png"></td><td></td><td></td><td></td><td></td><td></td><td>';
+print '</td></tr>'."\n";
+print '</table>'."\n";
+print '<table>'."\n";
+print '<tr>'."\n";
+
+//affichage des jours de la semaine en haut du tableau
+for($i = 0; $i < 7; $i++)
+{
+	print '<td align="center" class="joursemaine">'. dol_print_date(mktime(0,0,0,0, $i,10),'%A') .'</td>';
+}
+
+print '</tr>'."\n";
+
+//ajout d'une entrée dans la variable de session qui contient toutes les dates
+if (issetAndNoEmpty('choixjourajout')) {
+	if (!isset($_SESSION["totalchoixjour"])) {
+		$_SESSION["totalchoixjour"]=array();
+	}
+
+	// Test pour éviter les doublons dans la variable qui contient toutes les dates
+	$journeuf = true;
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) {
+				$journeuf=false;
+			}
+		}
+	}
+
+	// Si le test est passé, alors on insere la valeur dans la variable de session qui contient les dates
+	if ($journeuf && issetAndNoEmpty('choixjourajout') === true) {
+		array_push($_SESSION["totalchoixjour"], dol_mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"]));
+		sort($_SESSION["totalchoixjour"]);
+		$cle=array_search(dol_mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"]), $_SESSION["totalchoixjour"]);
+
+		//On sauvegarde les heures deja entrées
+		for ($i = 0; $i < $cle; $i++) {
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				if (issetAndNoEmpty('horaires'.$i) === true && issetAndNoEmpty($i, $_POST['horaires'.$i]) === true) {
+					$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+				}
+			}
+		}
+
+		for ($i = $cle; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			$k = $i + 1;
+			if (issetAndNoEmpty('horaires'.$i) === true && issetAndNoEmpty($i, $_POST['horaires'.$i]) === true) {
+				for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+					$_SESSION["horaires$k"][$j] = $_POST["horaires$i"][$j];
+				}
+			}
+		}
+
+		unset($_SESSION["horaires$cle"]);
+	}
+}
+
+//retrait d'une entrée dans la variable de session qui contient toutes les dates
+if (issetAndNoEmpty('choixjourretrait')) {
+	//On sauvegarde les heures deja entrées
+	for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+		//affichage des 5 cases horaires
+		for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+			$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+		}
+	}
+
+	for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+		if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"])) {
+			for ($j = $i; $j < count($_SESSION["totalchoixjour"]); $j++) {
+				$k = $j+1;
+				$_SESSION["horaires$j"] = $_SESSION["horaires$k"];
+			}
+
+			array_splice($_SESSION["totalchoixjour"], $i,1);
+		}
+	}
+}
+
+//report des horaires dans toutes les cases
+if (issetAndNoEmpty('reporterhoraires')) {
+	$_SESSION["horaires0"] = $_POST["horaires0"];
+	for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+		$j = $i+1;
+		$_SESSION["horaires$j"] = $_SESSION["horaires$i"];
+	}
+}
+
+//report des horaires dans toutes les cases
+if (issetAndNoEmpty('resethoraires')) {
+	for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+		unset ($_SESSION["horaires$i"]);
+	}
+}
+
+// affichage du calendrier
+print '<tr>'."\n";
+
+for ($i = 0; $i < $nbrejourmois + $premierjourmois; $i++) {
+	$numerojour = $i-$premierjourmois+1;
+
+	// On saute a la ligne tous les 7 jours
+	if (($i%7) == 0 && $i != 0) {
+		print '</tr><tr>'."\n";
+	}
+
+	// On affiche les jours precedants en gris et incliquables
+	if ($i < $premierjourmois) {
+		print '<td class="avant"></td>'."\n";
+	} else {
+		if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
+			for ($j = 0; $j < count($_SESSION["totalchoixjour"]); $j++) {
+				//affichage des boutons ROUGES
+				if (date("j", $_SESSION["totalchoixjour"][$j]) == $numerojour && date("n", $_SESSION["totalchoixjour"][$j]) == $_SESSION["mois"] && date("Y", $_SESSION["totalchoixjour"][$j]) == $_SESSION["annee"]) {
+					print '<td align="center" class="choisi"><input type="submit" class="bouton OFF" name="choixjourretrait[]" value="'.$numerojour.'"></td>'."\n";
+					$dejafait = $numerojour;
+				}
+			}
+		}
+
+		//Si pas de bouton ROUGE alors on affiche un bouton VERT ou GRIS avec le numéro du jour dessus
+		if (isset($dejafait) === false || $dejafait != $numerojour){
+			//bouton vert
+			if (($numerojour >= $jourAJ && $_SESSION["mois"] == $moisAJ && $_SESSION["annee"] == $anneeAJ) || ($_SESSION["mois"] > $moisAJ && $_SESSION["annee"] == $anneeAJ) || $_SESSION["annee"] > $anneeAJ) {
+				print '<td align="center" class="libre"><input type="submit" class="bouton ON" name="choixjourajout[]" value="'.$numerojour.'"></td>'."\n";
+			} else { //bouton gris
+				print '<td align="center" class="avant">'.$numerojour.'</td>'."\n";
+			}
+		}
+	}
+}
+
+//fin du tableau
+print '</tr>'."\n";
+print '</table>'."\n";
+print '</div></center>'."\n";
+
+//traitement de l'entrée des heures dans les cases texte
+$errheure = $erreur = false;
+if (issetAndNoEmpty('choixheures') || issetAndNoEmpty('choixheures_x')) {
+	//On sauvegarde les heures deja entrées
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+			}
+		}
+	}
+
+	//affichage des horaires
+	if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) {
+		for ($i = 0; $i < count($_SESSION["totalchoixjour"]); $i++) {
+			//affichage des 5 cases horaires
+			for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
+				$case = $j + 1;
+
+				if (isset($_POST['horaires'.$i]) === false || isset($_POST['horaires'.$i][$j]) === false) {
+					$errheure[$i][$j]=true;
+					$erreur=true;
+					$_SESSION["horaires$i"][$j]=$_POST["horaires$i"][$j];
+					continue;
+				}
+
+				//si c'est un creneau type 8:00-11:00
+				if (preg_match("/(\d{1,2}:\d{2})-(\d{1,2}:\d{2})/", $_POST["horaires$i"][$j], $creneaux)) {
+					//on recupere les deux parties du preg_match qu'on redécoupe autour des ":"
+					$debutcreneau=explode(":", $creneaux[1]);
+					$fincreneau=explode(":", $creneaux[2]);
+
+					//comparaison des heures de fin et de debut
+					//si correctes, on entre les données dans la variables de session
+					if ($debutcreneau[0] < 24 && $fincreneau[0] < 24 && $debutcreneau[1] < 60 && $fincreneau[1] < 60 && ($debutcreneau[0] < $fincreneau[0] || ($debutcreneau[0] == $fincreneau[0] && $debutcreneau[1] < $fincreneau[1]))) {
+						$_SESSION["horaires$i"][$j] = $creneaux[1].'-'.$creneaux[2];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif (preg_match(";^(\d{1,2}h\d{0,2})-(\d{1,2}h\d{0,2})$;i", $_POST["horaires$i"][$j], $creneaux)) { //si c'est un creneau type 8h00-11h00
+					//on recupere les deux parties du preg_match qu'on redécoupe autour des "H"
+					$debutcreneau=preg_split("/h/i", $creneaux[1]);
+					$fincreneau=preg_split("/h/i", $creneaux[2]);
+
+					//comparaison des heures de fin et de debut
+					//si correctes, on entre les données dans la variables de session
+					if ($debutcreneau[0] < 24 && $fincreneau[0] < 24 && $debutcreneau[1] < 60 && $fincreneau[1] < 60 && ($debutcreneau[0] < $fincreneau[0] || ($debutcreneau[0] == $fincreneau[0] && $debutcreneau[1] < $fincreneau[1]))) {
+						$_SESSION["horaires$i"][$j] = $creneaux[1].'-'.$creneaux[2];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif (preg_match(";^(\d{1,2}):(\d{2})$;", $_POST["horaires$i"][$j], $heures)) { //si c'est une heure simple type 8:00
+					//si valeures correctes, on entre les données dans la variables de session
+					if ($heures[1] < 24 && $heures[2] < 60) {
+						$_SESSION["horaires$i"][$j] = $heures[0];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif (preg_match(";^(\d{1,2})h(\d{0,2})$;i", $_POST["horaires$i"][$j], $heures)) { //si c'est une heure encore plus simple type 8h
+					//si valeures correctes, on entre les données dans la variables de session
+					if ($heures[1] < 24 && $heures[2] < 60) {
+						$_SESSION["horaires$i"][$j] = $heures[0];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif (preg_match(";^(\d{1,2})-(\d{1,2})$;", $_POST["horaires$i"][$j], $heures)) { //si c'est un creneau simple type 8-11
+					//si valeures correctes, on entre les données dans la variables de session
+					if ($heures[1] < $heures[2] && $heures[1] < 24 && $heures[2] < 24) {
+						$_SESSION["horaires$i"][$j] = $heures[0];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif (preg_match(";^(\d{1,2})h-(\d{1,2})h$;", $_POST["horaires$i"][$j], $heures)) { //si c'est un creneau H type 8h-11h
+					//si valeures correctes, on entre les données dans la variables de session
+					if ($heures[1] < $heures[2] && $heures[1] < 24 && $heures[2] < 24) {
+						$_SESSION["horaires$i"][$j] = $heures[0];
+					} else { //sinon message d'erreur et nettoyage de la case
+						$errheure[$i][$j]=true;
+						$erreur=true;
+					}
+				} elseif ($_POST["horaires$i"][$j]=="") { //Si la case est vide
+					unset($_SESSION["horaires$i"][$j]);
+				} else { //pour tout autre format, message d'erreur
+					//$errheure[$i][$j]=true;
+					//$erreur=true;
+					$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
+				}
+			}
+		}
+	}
+}
+
+print '<div class="bodydate"><center>'."\n";
+
+// affichage de tous les jours choisis
+if (issetAndNoEmpty('totalchoixjour', $_SESSION) && (!issetAndNoEmpty('choixheures_x') || $erreur))
+//if (1==1 || GETPOST($_SESSION['totalchoixjour']) && (! GETPOST('choixheures_x') || $erreur))
+{
+	//affichage des jours
+	print '<br>'."\n";
+	print '<strong>'. $langs->trans("SelectedDays") .' :</strong>'."<br>\n";
+	print $langs->trans("SelectDayDesc")."<br>\n";
+	print '<table>'."\n";
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+
+	for ($i = 0; $i < $_SESSION["nbrecaseshoraires"]; $i++) {
+		$j = $i+1;
+		print '<td classe="somme">'. $langs->trans("Time") .' '.$j.'</center></td>'."\n";
+	}
+
+	if ($_SESSION["nbrecaseshoraires"] < 10) {
+		print '<td classe="somme"><input type="image" name="ajoutcases" src="images/add-16.png"></td>'."\n";
+	}
+
+	print '</tr>'."\n";
+
+	//affichage de la liste des jours choisis
+	for ($i=0;$i<count($_SESSION["totalchoixjour"]);$i++)
+	{
+		print '<tr>'."\n";
+		print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>';
+
+		$affichageerreurfindeligne=false;
+
+		//affichage des cases d'horaires
+		for ($j=0;$j<$_SESSION["nbrecaseshoraires"];$j++) {
+			//si on voit une erreur, le fond de la case est rouge
+			if (isset($errheure[$i][$j]) && $errheure[$i][$j]) {
+				print '<td><input type=text size="10" maxlength="11" name=horaires'.$i.'[] value="'.$_SESSION["horaires$i"][$j].'" style="background-color:#FF6666;"></td>'."\n";
+				$affichageerreurfindeligne=true;
+			} else { //sinon la case est vide normalement
+				if (issetAndNoEmpty('horaires'.$i, $_SESSION) === false || issetAndNoEmpty($j, $_SESSION['horaires'.$i]) === false) {
+					if (issetAndNoEmpty('horaires'.$i, $_SESSION) === true) {
+						$_SESSION["horaires$i"][$j] = '';
+					} else {
+						$_SESSION["horaires$i"] = array();
+						$_SESSION["horaires$i"][$j] = '';
+					}
+				}
+
+				print '<td><input type=text size="10" maxlength="11" name=horaires'.$i.'[] value="'.$_SESSION["horaires$i"][$j].'"></td>'."\n";
+			}
+		}
+
+		if ($affichageerreurfindeligne) {
+			print '<td><b><font color=#FF0000>'. _("Bad format!") .'</font></b></td>'."\n";
+		}
+
+		print '</tr>'."\n";
+	}
+
+	print '</table>'."\n";
+
+	//affichage des boutons de formulaire pour annuler, effacer les jours ou créer le sondage
+	print '<table>'."\n";
+	print '<tr>'."\n";
+	print '<td><input type="submit" class="button" name="reset" value="'. dol_escape_htmltag($langs->trans("RemoveAllDays")) .'"></td><td><input type="submit" class="button" name="reporterhoraires" value="'. dol_escape_htmltag($langs->trans("CopyHoursOfFirstDay")) .'"></td><td><input type="submit" class="button" name="resethoraires" value="'. dol_escape_htmltag($langs->trans("RemoveAllHours")) .'"></td></tr>'."\n";
+	print'<tr><td colspan="3"><br><br></td></tr>'."\n";
+	print '<tr><td colspan="3" align="center"><input type="submit" class="button" name="choixheures" value="'. $langs->trans("NextStep"). '"></td></tr>'."\n";
+	print '</table>'."\n";
+
+	//si un seul jour et aucunes horaires choisies, : message d'erreur
+	if ((GETPOST('choixheures') || GETPOST('choixheures_x')) && (count($_SESSION["totalchoixjour"])=="1" && $_POST["horaires0"][0]=="" && $_POST["horaires0"][1]=="" && $_POST["horaires0"][2]=="" && $_POST["horaires0"][3]=="" && $_POST["horaires0"][4]=="")) {
+		print '<table><tr><td colspan=3><font color=#FF0000>'. _("Enter more choices for the voters") .'</font><br></td></tr></table>'."\n";
+		$erreur=true;
+	}
+}
+
+//s'il n'y a pas d'erreur et que le bouton de creation est activé, on demande confirmation
+if (!$erreur  && (GETPOST('choixheures') || GETPOST('choixheures_x'))) {
+	$taille_tableau=count($_SESSION["totalchoixjour"])-1;
+	$jour_arret = $_SESSION["totalchoixjour"][$taille_tableau]+200000;
+	$date_fin=dol_print_date($jour_arret, 'dayhourtext');
+
+	print '<br><div class="presentationdatefin">'. $langs->trans("PollWillExpire",2) .'</td></tr><tr><td><br>'. $langs->trans("RemovalDate") .' : <b> '.$date_fin.'</b><br>'."\n";
+	print '</div>'."\n";
+	print '<div class="presentationdatefin">'."\n";
+	print '<font color="#FF0000">'. _("Once you have confirmed the creation of your poll, you will be automatically redirected on the page of your poll. <br>Then, you will receive quickly an email contening the link to your poll for sending it to the voters.") .'</font>'."\n";
+	print'</div>'."\n";
+	// print'<p class=affichageexport>'."\n";
+	// print 'Pour finir la cr&eacute;ation du sondage, cliquez sur le bouton <img src="images/add-16.png" alt="ajout"> ci-dessous'."\n";
+	// print '</p>'."\n";
+	print '<table>'."\n";
+	print '<tr><td>'. $langs->trans("BackToHoursSetup") .'</td><td></td><td><input type="image" name="retourhoraires" src="images/back-32.png"></td></tr>'."\n";
+	print'<tr><td>'. $langs->trans("CreatePoll") .'</td><td></td><td><input type="image" name="confirmation" value="Valider la cr&eacute;ation" src="images/add.png"></td></tr>'."\n";
+	print '</table>'."\n";
+}
+
+print '</tr>'."\n";
+print '</table>'."\n";
+print '<a name=bas></a>'."\n";
+//fin du formulaire et bandeau de pied
+print '</form>'."\n";
+//bandeau de pied
+print '<br><br><br><br>'."\n";
+print '</center></div>'."\n";
+
+llxFooterSurvey();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/public/create_survey.php b/htdocs/opensurvey/public/create_survey.php
new file mode 100755
index 0000000000000000000000000000000000000000..729255a6ca19bd44c592f0f0450bd352d6a01453
--- /dev/null
+++ b/htdocs/opensurvey/public/create_survey.php
@@ -0,0 +1,199 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/public/create_survey.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to create a new survey
+ */
+
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+$langs->load("opensurvey@opensurvey");
+
+$origin=GETPOST('origin','alpha');
+
+
+// On teste toutes les variables pour supprimer l'ensemble des warnings PHP
+// On transforme en entites html les données afin éviter les failles XSS
+$post_var = array('titre', 'nom', 'adresse', 'commentaires', 'canedit', 'mailsonde', 'creation_sondage_date', 'creation_sondage_date_x', 'creation_sondage_autre', 'creation_sondage_autre_x');
+foreach ($post_var as $var)
+{
+	$$var = GETPOST($var);
+}
+
+// On initialise egalement la session car sinon bonjour les warning :-)
+$session_var = array('titre', 'nom', 'adresse', 'commentaires', 'mailsonde', 'canedit');
+foreach ($session_var as $var)
+{
+	if (isset($_SESSION[$var])) $_SESSION[$var] = null;
+}
+
+// On initialise également les autres variables
+$erreur_adresse = false;
+$erreur_injection_titre = false;
+$erreur_injection_nom = false;
+$erreur_injection_commentaires = false;
+$cocheplus = '';
+$cochemail = '';
+
+// Jump to correct page
+if (GETPOST("creation_sondage_date") || GETPOST("creation_sondage_autre") || GETPOST("creation_sondage_date_x") || GETPOST("creation_sondage_autre_x"))
+{
+	$_SESSION["titre"] = $titre;
+	$_SESSION["nom"] = $nom;
+	$_SESSION["adresse"] = $adresse;
+	$_SESSION["commentaires"] = $commentaires;
+
+	unset($_SESSION["canedit"]);
+	$_SESSION["canedit"] = $canedit;
+
+	unset($_SESSION["mailsonde"]);
+	if ($mailsonde !== null) {
+		$_SESSION["mailsonde"] = true;
+	} else {
+		$_SESSION["mailsonde"] = false;
+	}
+
+	if(validateEmail($adresse) === false) {
+		$erreur_adresse = true;
+	}
+
+	//var_dump($titre.' - '.$nom.' - '.$adresse.' - '.!$erreur_adresse.' - '.! $erreur_injection_titre.' - '.! $erreur_injection_commentaires.' - '.! $erreur_injection_nom.' - '.$creation_sondage_date.' - '.$creation_sondage_autre); exit;
+
+	if ($titre && $nom && $adresse && !$erreur_adresse && ! $erreur_injection_titre && ! $erreur_injection_commentaires && ! $erreur_injection_nom)
+	{
+		if (! empty($creation_sondage_date))
+		{
+			header("Location: choix_date.php".($origin?'?origin='.$origin:''));
+			exit();
+		}
+
+		if (! empty($creation_sondage_autre))
+		{
+			header("Location: choix_autre.php".($origin?'?origin='.$origin:''));
+			exit();
+		}
+	}
+}
+
+
+
+
+/*
+ * View
+ */
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeaderSurvey($langs->trans("OpenSurvey"), "", 0, 0, $arrayofjs, $arrayofcss);
+
+
+print '<div class="bandeautitre">'. $langs->trans("CreatePoll").' (1 / 2)' .'</div>'."\n";
+
+
+//debut du formulaire
+print '<form name="formulaire" action="create_survey.php" method="POST" onkeypress="javascript:process_keypress(event)">'."\n";
+print '<input type="hidden" name="origin" value="'.dol_escape_htmltag($origin).'">';
+
+print '<div class=corps>'."\n";
+print '<br>'. $langs->trans("YouAreInPollCreateArea") .'<br><br>'."\n";
+
+//Affichage des différents champs textes a remplir
+print '<table>'."\n";
+
+print '<tr><td class="fieldrequired">'. $langs->trans("PollTitle") .'</td><td><input type="text" name="titre" size="40" maxlength="80" value="'.$_SESSION["titre"].'"></td>'."\n";
+if (! $_SESSION["titre"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre') || GETPOST('creation_sondage_date_x') || GETPOST('creation_sondage_autre_x')))
+{
+	print "<td><font color=\"#FF0000\">" . $langs->trans("FieldMandatory") . "</font></td>"."\n";
+}
+
+print '</tr>'."\n";
+print '<tr><td>'. $langs->trans("Description") .'</td><td><textarea name="commentaires" rows="7" cols="40">'.$_SESSION["commentaires"].'</textarea></td>'."\n";
+print '</tr>'."\n";
+print '<tr><td class="fieldrequired">'. $langs->trans("OpenSurveyYourName") .'</td><td>';
+
+print '<input type="text" name="nom" size="40" maxlength="40" value="'.$_SESSION["nom"].'"></td>'."\n";
+
+if (! $_SESSION["nom"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre') || GETPOST('creation_sondage_date_x') || GETPOST('creation_sondage_autre_x')))
+{
+	print "<td><font color=\"#FF0000\">" . $langs->trans("FieldMandatory")  . "</font></td>"."\n";
+}
+
+print '</tr>'."\n";
+print '<tr><td class="fieldrequired">'.  $langs->trans("OpenSurveyYourEMail")  .'</td><td>';
+
+print '<input type="text" name="adresse" size="40" maxlength="64" value="'.$_SESSION["adresse"].'"></td>'."\n";
+
+if (!$_SESSION["adresse"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre') || GETPOST('creation_sondage_date_x') || GETPOST('creation_sondage_autre_x')))
+{
+  print "<td><font color=\"#FF0000\">" .$langs->trans("FieldMandatory")  . " </font></td>"."\n";
+} elseif ($erreur_adresse && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre') || GETPOST('creation_sondage_date_x') || GETPOST('creation_sondage_autre_x')))
+{
+  print "<td><font color=\"#FF0000\">" . _("The address is not correct! (You should enter a valid email address in order to receive the link to your poll)") . "</font></td>"."\n";
+}
+
+print '</tr>'."\n";
+print '</table>'."\n";
+
+//focus javascript sur le premier champ
+print '<script type="text/javascript">'."\n";
+print 'document.formulaire.titre.focus();'."\n";
+print '</script>'."\n";
+
+print '<br>'."\n";
+
+// Check or not
+$cocheplus='';
+if ($_SESSION["canedit"]) $cocheplus="checked";
+
+print '<input type="checkbox" name="canedit" '.$cocheplus.'>'. $langs->trans("VotersCanModify") .'<br>'."\n";
+
+if ($_SESSION["mailsonde"]) $cochemail="checked";
+
+print '<input type=checkbox name=mailsonde '.$cochemail.'>'. $langs->trans("ToReceiveEMailForEachVote") .'<br>'."\n";
+
+if (GETPOST('choix_sondage'))
+{
+	if (GETPOST('choix_sondage') == 'date') print '<input type="hidden" name="creation_sondage_date" value="date">';
+	else print '<input type="hidden" name="creation_sondage_autre" value="autre">';
+	print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">';
+	print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date'?$langs->trans("TypeDate"):$langs->trans("TypeClassic")).')">';
+}
+else
+{
+	//affichage des boutons pour choisir sondage date ou autre
+	print '<br><table >'."\n";
+	print '<tr><td>'. _("Schedule an event") .'</td><td></td> '."\n";
+	print '<td><input type="image" name="creation_sondage_date" value="Trouver une date" src="images/calendar-32.png"></td></tr>'."\n";
+	print '<tr><td>'. _("Make a choice") .'</td><td></td> '."\n";
+	print '<td><input type="image" name="creation_sondage_autre" value="'. _('Make a poll') . '" src="images/chart-32.png"></td></tr>'."\n";
+	print '</table>'."\n";
+}
+print '<br><br><br>'."\n";
+print '</div>'."\n";
+print '</form>'."\n";
+
+llxFooterSurvey();
+
+$db->close();
+?>
diff --git a/htdocs/opensurvey/public/exportcsv.php b/htdocs/opensurvey/public/exportcsv.php
new file mode 100755
index 0000000000000000000000000000000000000000..f933b37a3170c00d1f680aa559000ceeb7d57db7
--- /dev/null
+++ b/htdocs/opensurvey/public/exportcsv.php
@@ -0,0 +1,153 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/public/exportcsv.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to list surveys
+ */
+
+
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php");
+
+$action=GETPOST('action');
+$numsondage = $numsondageadmin = '';
+if (GETPOST('sondage'))
+{
+	if (strlen(GETPOST('sondage')) == 24)	// recuperation du numero de sondage admin (24 car.) dans l'URL
+	{
+		$numsondageadmin=GETPOST("sondage",'alpha');
+		$numsondage=substr($numsondageadmin, 0, 16);
+	}
+	else
+	{
+		$numsondageadmin='';
+		$numsondage=GETPOST("sondage",'alpha');
+	}
+}
+
+$object=new Opensurveysondage($db);
+$result=$object->fetch(0,$numsondage);
+if ($result <= 0) dol_print_error('','Failed to get survey id '.$numsondage);
+
+
+/*
+ * Actions
+ */
+
+
+
+/*
+ * View
+ */
+
+$now=dol_now();
+
+$nbcolonnes=substr_count($object->sujet,',')+1;
+$toutsujet=explode(",",$object->sujet);
+
+// affichage des sujets du sondage
+$input.=$langs->trans("Name").";";
+for ($i=0;$toutsujet[$i];$i++)
+{
+	if ($object->format=="D"||$object->format=="D+")
+	{
+		$input.=''.dol_print_date($toutsujet[$i],'dayhour').';';
+	} else {
+		$input.=''.$toutsujet[$i].';';
+	}
+}
+
+$input.="\r\n";
+
+if (strpos($object->sujet,'@') !== false)
+{
+	$input.=";";
+	for ($i=0;$toutsujet[$i];$i++)
+	{
+		$heures=explode("@",$toutsujet[$i]);
+		$input.=''.$heures[1].';';
+	}
+
+	$input.="\r\n";
+}
+
+
+$sql ='SELECT nom, reponses';
+$sql.=' FROM '.MAIN_DB_PREFIX."opensurvey_user_studs";
+$sql.=" WHERE id_sondage='" . $db->escape($numsondage) . "'";
+$sql.=" ORDER BY id_users";
+dol_syslog("sql=".$sql);
+$resql=$db->query($sql);
+if ($resql)
+{
+	$num=$db->num_rows($resql);
+	$i=0;
+	while ($i < $num)
+	{
+		$obj=$db->fetch_object($resql);
+
+		// Le nom de l'utilisateur
+		$nombase=str_replace("°","'",$obj->nom);
+		$input.=$nombase.';';
+
+		//affichage des resultats
+		$ensemblereponses=$obj->reponses;
+		for ($k=0;$k<$nbcolonnes;$k++)
+		{
+			$car=substr($ensemblereponses,$k,1);
+			if ($car == "1")
+			{
+				$input.='OK;';
+				$somme[$k]++;
+			}
+			else if ($car == "2")
+			{
+				$input.='KO;';
+				$somme[$k]++;
+			}
+			else
+			{
+				$input.=';';
+			}
+		}
+
+		$input.="\r\n";
+		$i++;
+	}
+}
+else dol_print_error($db);
+
+
+$filesize = strlen($input);
+$filename=$numsondage."_".dol_print_date($now,'%Y%m%d%H%M').".csv";
+
+
+
+header('Content-Type: text/csv; charset=utf-8');
+header('Content-Length: '.$filesize);
+header('Content-Disposition: attachment; filename="'.$filename.'"');
+header('Cache-Control: max-age=10');
+echo $input;
+
+exit;
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/public/images/accept-24.png b/htdocs/opensurvey/public/images/accept-24.png
new file mode 100755
index 0000000000000000000000000000000000000000..65ca043ee12627bd42bb6e8563fb73ed61e07d06
Binary files /dev/null and b/htdocs/opensurvey/public/images/accept-24.png differ
diff --git a/htdocs/opensurvey/public/images/accept-32.png b/htdocs/opensurvey/public/images/accept-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..c94c066edee91b802be27455483a21113fd1c1eb
Binary files /dev/null and b/htdocs/opensurvey/public/images/accept-32.png differ
diff --git a/htdocs/opensurvey/public/images/accept.png b/htdocs/opensurvey/public/images/accept.png
new file mode 100755
index 0000000000000000000000000000000000000000..ada57a9ae60ebccf4cf8f4fcb9523cffbc6c51d0
Binary files /dev/null and b/htdocs/opensurvey/public/images/accept.png differ
diff --git a/htdocs/opensurvey/public/images/add-16.png b/htdocs/opensurvey/public/images/add-16.png
new file mode 100755
index 0000000000000000000000000000000000000000..23d5bed776023cee0402e7c0b1649d57704e36d3
Binary files /dev/null and b/htdocs/opensurvey/public/images/add-16.png differ
diff --git a/htdocs/opensurvey/public/images/add-24.png b/htdocs/opensurvey/public/images/add-24.png
new file mode 100755
index 0000000000000000000000000000000000000000..c63af7f39062ad0d5b9f1c5f9afa617e7ada0d5d
Binary files /dev/null and b/htdocs/opensurvey/public/images/add-24.png differ
diff --git a/htdocs/opensurvey/public/images/add.png b/htdocs/opensurvey/public/images/add.png
new file mode 100755
index 0000000000000000000000000000000000000000..7409ef332d2435c3fb43c879a80c9fcb5820f796
Binary files /dev/null and b/htdocs/opensurvey/public/images/add.png differ
diff --git a/htdocs/opensurvey/public/images/back-32.png b/htdocs/opensurvey/public/images/back-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..b44fbb2385acd6ba9eec5f4c00e47cc5518b23dc
Binary files /dev/null and b/htdocs/opensurvey/public/images/back-32.png differ
diff --git a/htdocs/opensurvey/public/images/calendar-32.png b/htdocs/opensurvey/public/images/calendar-32.png
new file mode 100644
index 0000000000000000000000000000000000000000..89761150635adaf8ef0434c9fcb1175ccc0aad04
Binary files /dev/null and b/htdocs/opensurvey/public/images/calendar-32.png differ
diff --git a/htdocs/opensurvey/public/images/cancel.png b/htdocs/opensurvey/public/images/cancel.png
new file mode 100755
index 0000000000000000000000000000000000000000..c149c2bc017d5ce5a8ae9330dd7dbd012482e0f4
Binary files /dev/null and b/htdocs/opensurvey/public/images/cancel.png differ
diff --git a/htdocs/opensurvey/public/images/chart-32.png b/htdocs/opensurvey/public/images/chart-32.png
new file mode 100644
index 0000000000000000000000000000000000000000..1406b8da933f7ee21f09bf55ce4e81ce3312e54f
Binary files /dev/null and b/htdocs/opensurvey/public/images/chart-32.png differ
diff --git a/htdocs/opensurvey/public/images/csv.png b/htdocs/opensurvey/public/images/csv.png
new file mode 100755
index 0000000000000000000000000000000000000000..f90ef25ec7f1cb0fdae38d9fe2d9edeee9928ef1
Binary files /dev/null and b/htdocs/opensurvey/public/images/csv.png differ
diff --git a/htdocs/opensurvey/public/images/date.png b/htdocs/opensurvey/public/images/date.png
new file mode 100644
index 0000000000000000000000000000000000000000..c847011e952571975f53e89e9cdaa8852f1b874f
Binary files /dev/null and b/htdocs/opensurvey/public/images/date.png differ
diff --git a/htdocs/opensurvey/public/images/fforward.png b/htdocs/opensurvey/public/images/fforward.png
new file mode 100755
index 0000000000000000000000000000000000000000..369084cdf149b47c66e5ef6dc31a21876f3feb40
Binary files /dev/null and b/htdocs/opensurvey/public/images/fforward.png differ
diff --git a/htdocs/opensurvey/public/images/ical.png b/htdocs/opensurvey/public/images/ical.png
new file mode 100755
index 0000000000000000000000000000000000000000..b092a75b6da3e338621c548c4620c143df9f5cc6
Binary files /dev/null and b/htdocs/opensurvey/public/images/ical.png differ
diff --git a/htdocs/opensurvey/public/images/info.png b/htdocs/opensurvey/public/images/info.png
new file mode 100755
index 0000000000000000000000000000000000000000..4c665a4f0a10633d475480553f673bceb10f594a
Binary files /dev/null and b/htdocs/opensurvey/public/images/info.png differ
diff --git a/htdocs/opensurvey/public/images/logo_uds_bandeau.gif b/htdocs/opensurvey/public/images/logo_uds_bandeau.gif
new file mode 100755
index 0000000000000000000000000000000000000000..3132c13a75a91be0d8a555378ddcd370e6828b29
Binary files /dev/null and b/htdocs/opensurvey/public/images/logo_uds_bandeau.gif differ
diff --git a/htdocs/opensurvey/public/images/logo_uds_lettre.jpg b/htdocs/opensurvey/public/images/logo_uds_lettre.jpg
new file mode 100755
index 0000000000000000000000000000000000000000..d8a31692e0e86914df08d08897e375a8bb7a101f
Binary files /dev/null and b/htdocs/opensurvey/public/images/logo_uds_lettre.jpg differ
diff --git a/htdocs/opensurvey/public/images/medaille.png b/htdocs/opensurvey/public/images/medaille.png
new file mode 100755
index 0000000000000000000000000000000000000000..97a22b72eea2e8d65655993c68a9e03f6a40aa9e
Binary files /dev/null and b/htdocs/opensurvey/public/images/medaille.png differ
diff --git a/htdocs/opensurvey/public/images/next-32.png b/htdocs/opensurvey/public/images/next-32.png
new file mode 100755
index 0000000000000000000000000000000000000000..934a254f307b0d140219e13c723a4fc6836ed881
Binary files /dev/null and b/htdocs/opensurvey/public/images/next-32.png differ
diff --git a/htdocs/opensurvey/public/images/next.png b/htdocs/opensurvey/public/images/next.png
new file mode 100755
index 0000000000000000000000000000000000000000..24d94e830a33157c791a714ab60565f9aebf0d6e
Binary files /dev/null and b/htdocs/opensurvey/public/images/next.png differ
diff --git a/htdocs/opensurvey/public/images/previous.png b/htdocs/opensurvey/public/images/previous.png
new file mode 100755
index 0000000000000000000000000000000000000000..b4b79aeec517f11788920581a3b6044a2bf80930
Binary files /dev/null and b/htdocs/opensurvey/public/images/previous.png differ
diff --git a/htdocs/opensurvey/public/images/reload.png b/htdocs/opensurvey/public/images/reload.png
new file mode 100755
index 0000000000000000000000000000000000000000..9a2b2e82d365739d12d026dba599afa059bf2486
Binary files /dev/null and b/htdocs/opensurvey/public/images/reload.png differ
diff --git a/htdocs/opensurvey/public/images/rewind.png b/htdocs/opensurvey/public/images/rewind.png
new file mode 100755
index 0000000000000000000000000000000000000000..99ed78c3c915ee96c26064aa45e8adc235f6c63e
Binary files /dev/null and b/htdocs/opensurvey/public/images/rewind.png differ
diff --git a/htdocs/opensurvey/public/images/sondage2.png b/htdocs/opensurvey/public/images/sondage2.png
new file mode 100644
index 0000000000000000000000000000000000000000..8018ce99860bc7488da3c835e0984301cb11b7d5
Binary files /dev/null and b/htdocs/opensurvey/public/images/sondage2.png differ
diff --git a/htdocs/opensurvey/public/index.php b/htdocs/opensurvey/public/index.php
new file mode 100755
index 0000000000000000000000000000000000000000..1d31bf260b3760f70c04b1131d575444178cdf94
--- /dev/null
+++ b/htdocs/opensurvey/public/index.php
@@ -0,0 +1,61 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+//if (! defined('NOREQUIREUSER'))  define('NOREQUIREUSER','1');
+//if (! defined('NOREQUIREDB'))    define('NOREQUIREDB','1');
+//if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
+//if (! defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN','1');
+if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
+if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1'); // If there is no menu to show
+if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
+if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+$origin=GETPOST('origin','alpha');
+
+
+/*
+ * View
+ */
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeaderSurvey($langs->trans("OpenSurvey"), "", 0, 0, $arrayofjs, $arrayofcss);
+
+print '<center>
+<form name="formulaire" action="create_survey.php" method="POST">
+<input type="hidden" name="origin" value="'.dol_escape_htmltag($origin).'">
+<div id="interface-header" style="">
+<p id="application-description" class="pp-gris-fonce2">'.$langs->trans("OpenSurveyDesc").' '.$langs->trans("OpenSurveyNoRegistration").'</p>
+</div><br>';
+print $langs->trans("OrganizeYourMeetingEasily").'
+<div class="corps">
+<br>
+<div class="index_date"><div><img class="opacity" src="images/date.png" onclick="document.formulaire.date.click()"></div><button id="date" name="choix_sondage" value="date" type="submit" class="button orange bigrounded"><img src="images/calendar-32.png" alt=""><strong>&nbsp;Créer un sondage spécial dates</strong></button></div><div class="index_sondage"><div><img class="opacity" src="images/sondage2.png" onclick="document.formulaire.autre.click()"></div><button id="autre" name="choix_sondage" value="autre" type="submit" class="button blue bigrounded"><img src="images/chart-32.png" alt=""><strong>&nbsp;Créer un sondage classique</strong></button></div><div style="clear:both;"></div>
+</div>
+</form></center>';
+
+llxFooterSurvey();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/public/studs.php b/htdocs/opensurvey/public/studs.php
new file mode 100755
index 0000000000000000000000000000000000000000..9a20b14031b18bf6749240c6c8d274ab81b508b1
--- /dev/null
+++ b/htdocs/opensurvey/public/studs.php
@@ -0,0 +1,713 @@
+<?php
+/* Copyright (C) 2013      Laurent Destailleur <eldy@users.sourceforge.net>
+ *
+ * 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
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/opensurvey/public/studs.php
+ *	\ingroup    opensurvey
+ *	\brief      Page to list surveys
+ */
+
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+require_once('../../main.inc.php');
+require_once(DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php");
+require_once(DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php");
+
+
+// Init vars
+$action=GETPOST('action');
+$numsondage = $numsondageadmin = '';
+if (GETPOST('sondage'))
+{
+	if (strlen(GETPOST('sondage')) == 24)	// recuperation du numero de sondage admin (24 car.) dans l'URL
+	{
+		$numsondageadmin=GETPOST("sondage",'alpha');
+		$numsondage=substr($numsondageadmin, 0, 16);
+	}
+	else
+	{
+		$numsondageadmin='';
+		$numsondage=GETPOST("sondage",'alpha');
+	}
+}
+
+$object=new Opensurveysondage($db);
+$result=$object->fetch(0,$numsondage);
+if ($result <= 0) dol_print_error('','Failed to get survey id '.$numsondage);
+
+
+$nbcolonnes = substr_count($object->sujet, ',') + 1;
+
+
+
+/*
+ * Actions
+ */
+
+$listofvoters=explode(',',$_SESSION["savevoter"]);
+
+// Add comment
+if (GETPOST('ajoutcomment'))
+{
+	$error=0;
+
+	if (! GETPOST('comment'))
+	{
+		$error++;
+		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Comment")),'errors');
+	}
+	if (! GETPOST('commentuser'))
+	{
+		$error++;
+		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("User")),'errors');
+	}
+
+	if (! $error)
+	{
+		$comment = GETPOST("comment");
+		$comment_user = GETPOST('commentuser');
+
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)";
+		$sql.= " VALUES ('".$db->escape($numsondage)."','".$db->escape($comment)."','".$db->escape($comment_user)."')";
+		$resql = $db->query($sql);
+		dol_syslog("sql=".$sql);
+		if (! $resql) dol_print_error($db);
+	}
+}
+
+// Add vote
+if (isset($_POST["boutonp"]) || isset($_POST["boutonp_x"]))
+{
+	//Si le nom est bien entré
+	if (GETPOST('nom'))
+	{
+		$nouveauchoix = '';
+		for ($i=0;$i<$nbcolonnes;$i++)
+		{
+			if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
+			{
+				$nouveauchoix.="1";
+			}
+			else if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2')
+			{
+				$nouveauchoix.="2";
+			}
+			else { // sinon c'est 0
+				$nouveauchoix.="0";
+			}
+		}
+
+		$nom=substr($_POST["nom"],0,64);
+
+		// Check if vote already exists
+		$sql = 'SELECT id_users, nom FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage='".$db->escape($numsondage)."' AND nom = '".$db->escape($nom)."' ORDER BY id_users";
+		$resql = $db->query($sql);
+		$num_rows = $db->num_rows($resql);
+		if ($num_rows > 0)
+		{
+			setEventMessage($langs->trans("VoteNameAlreadyExists"),'errors');
+			$error++;
+		}
+		else
+		{
+			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)';
+			$sql.= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')";
+			$resql=$db->query($sql);
+
+			if ($resql)
+			{
+				// Add voter to session
+				$_SESSION["savevoter"]=$nom.','.(empty($_SESSION["savevoter"])?'':$_SESSION["savevoter"]);	// Save voter
+				$listofvoters=explode(',',$_SESSION["savevoter"]);
+
+				if (! empty($object->mailsonde))
+				{
+					include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
+					$cmailfile=new CMailFile("[".DOL_APPLICATION_TITLE."] ".$langs->trans("Poll").': '.$object->titre, $object->mail_admin, $conf->global->MAIN_MAIL_EMAIL_FROM, $nom." has filled a line.\nou can find your poll at the link:\n".getUrlSondage($numsondage));
+					$result=$cmailfile->sendfile();
+					if ($result)
+					{
+
+					}
+					else
+					{
+
+					}
+				}
+			}
+			else dol_print_error($db);
+		}
+	}
+	else
+	{
+		$err |= NAME_EMPTY;
+	}
+}
+
+
+// Update vote
+$sql = 'SELECT * FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users';
+$sql = $connect->Prepare($sql);
+$user_studs = $connect->Execute($sql, array($numsondage));
+$nblignes = $user_studs->RecordCount();
+$testmodifier = false;
+$ligneamodifier = -1;
+for ($i=0; $i<$nblignes; $i++)
+{
+	if (isset($_POST['modifierligne'.$i])) {
+		$ligneamodifier = $i;
+	}
+
+	//test pour voir si une ligne est a modifier
+	if (isset($_POST['validermodifier'.$i])) {
+		$modifier = $i;
+		$testmodifier = true;
+	}
+}
+
+if ($testmodifier)
+{
+	//var_dump($_POST);exit;
+	$nouveauchoix = '';
+	for ($i=0;$i<$nbcolonnes;$i++)
+	{
+		//var_dump($_POST["choix$i"]);
+		if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
+		{
+			$nouveauchoix.="1";
+		}
+		else if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2')
+		{
+			$nouveauchoix.="2";
+		}
+		else { // sinon c'est 0
+			$nouveauchoix.="0";
+		}
+	}
+
+	$compteur=0;
+	while ($data = $user_studs->FetchNextObject(false) )
+	{
+		if ($compteur == $modifier)
+		{
+			$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_user_studs";
+			$sql.= " SET reponses = '".$db->escape($nouveauchoix)."'";
+			$sql.= " WHERE nom = '".$db->escape($data->nom)."' AND id_users = '".$db->escape($data->id_users)."'";
+			$resql = $db->query($sql);
+			if ($resql <= 0)
+			{
+				dol_print_error($db);
+				exit;
+			}
+
+			if ($object->mailsonde=="yes")
+			{
+				// TODO Use CMailFile
+				//$headers="From: ".NOMAPPLICATION." <".ADRESSEMAILADMIN.">\r\nContent-Type: text/plain; charset=\"UTF-8\"\nContent-Transfer-Encoding: 8bit";
+				//mail ("$object->mail_admin", "[".NOMAPPLICATION."] " . _("Poll's participation") . " : $object->titre", "\"$data->nom\""."" . _("has filled a line.\nYou can find your poll at the link") . " :\n\n".getUrlSondage($numsondage)." \n\n" . _("Thanks for your confidence.") . "\n".NOMAPPLICATION,$headers);
+			}
+		}
+
+		$compteur++;
+	}
+}
+
+// Delete comment
+$idcomment=GETPOST('deletecomment','int');
+if ($idcomment)
+{
+	$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$idcomment;
+	$resql = $db->query($sql);
+}
+
+
+
+/*
+ * View
+ */
+
+$form=new Form($db);
+$object=new OpenSurveySondage($db);
+
+$arrayofjs=array();
+$arrayofcss=array('/opensurvey/css/style.css');
+llxHeaderSurvey($object->titre, "", 0, 0, $arrayofjs, $arrayofcss);
+
+$res=$object->fetch(0,$numsondage);
+
+if ($res <= 0)
+{
+	print $langs->trans("ErrorPollDoesNotExists",$numsondage);
+	llxFooterSurvey();
+	exit;
+}
+
+// Define format of choices
+$toutsujet=explode(",",$object->sujet);
+$toutsujet=str_replace("°","'",$toutsujet);
+
+$listofanswers=array();
+foreach ($toutsujet as $value)
+{
+	$tmp=explode('@',$value);
+	$listofanswers[]=array('label'=>$tmp[0],'format'=>($tmp[1]?$tmp[1]:'checkbox'));
+}
+
+
+print '<div class="survey_invitation">'.$langs->trans("YouAreInivitedToVote").'</div>';
+print $langs->trans("OpenSurveyHowTo").'<br><br>';
+
+print '<div class="corps"> '."\n";
+
+//affichage du titre du sondage
+$titre=str_replace("\\","",$object->titre);
+print '<strong>'.$titre.'</strong><br>'."\n";
+
+//affichage du nom de l'auteur du sondage
+print $langs->trans("InitiatorOfPoll") .' : '.$object->nom_admin.'<br>'."\n";
+
+//affichage des commentaires du sondage
+if ($object->commentaires) {
+	print '<br>'.$langs->trans("Description") .' :<br>'."\n";
+	$commentaires=dol_nl2br($object->commentaires);
+	print $commentaires;
+	print '<br>'."\n";
+}
+
+print '</div>'."\n";
+
+print '<form name="formulaire" action="studs.php?sondage='.$numsondage.'"'.'#bas" method="POST" onkeypress="javascript:process_keypress(event)">'."\n";
+print '<input type="hidden" name="sondage" value="' . $numsondage . '"/>';
+// Todo : add CSRF protection
+print '<div class="cadre"> '."\n";
+print '<br><br>'."\n";
+
+// Debut de l'affichage des resultats du sondage
+print '<table class="resultats">'."\n";
+
+//recuperation des utilisateurs du sondage
+$sql = 'SELECT * FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users';
+$sql = $connect->Prepare($sql);
+$user_studs = $connect->Execute($sql, array($numsondage));
+
+//si le sondage est un sondage de date
+if ($object->format=="D"||$object->format=="D+")
+{
+	//affichage des sujets du sondage
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des années
+	$colspan=1;
+	for ($i=0;$i<count($toutsujet);$i++)
+	{
+		if (isset($toutsujet[$i+1]) && date('Y', intval($toutsujet[$i])) == date('Y', intval($toutsujet[$i+1]))) {
+			$colspan++;
+		} else {
+			print '<td colspan='.$colspan.' class="annee">'.date('Y', intval($toutsujet[$i])).'</td>'."\n";
+			$colspan=1;
+		}
+	}
+
+	print '</tr>'."\n";
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des mois
+	$colspan=1;
+	for ($i=0;$i<count($toutsujet);$i++) {
+		$cur = intval($toutsujet[$i]);	// intval() est utiliser pour supprimer le suffixe @* qui déplaît logiquement à strftime()
+
+		if (isset($toutsujet[$i+1]) === false) {
+			$next = false;
+		} else {
+			$next = intval($toutsujet[$i+1]);
+		}
+
+		if ($next && dol_print_date($cur, "%B") == dol_print_date($next, "%B") && dol_print_date($cur, "%Y") == dol_print_date($next, "%Y")){
+			$colspan++;
+		} else {
+			print '<td colspan='.$colspan.' class="mois">'.dol_print_date($cur, "%B").'</td>'."\n";
+			$colspan=1;
+		}
+	}
+
+	print '</tr>'."\n";
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+
+	//affichage des jours
+	$colspan=1;
+	for ($i=0;$i<count($toutsujet);$i++) {
+		$cur = intval($toutsujet[$i]);
+		if (isset($toutsujet[$i+1]) === false) {
+			$next = false;
+		} else {
+			$next = intval($toutsujet[$i+1]);
+		}
+		if ($next && dol_print_date($cur, "%a %e") == dol_print_date($next,"%a %e") && dol_print_date($cur, "%B") == dol_print_date($next, "%B")) {
+			$colspan++;
+		} else {
+			print '<td colspan="'.$colspan.'" class="jour">'.dol_print_date($cur, "%a %e").'</td>'."\n";
+			$colspan=1;
+		}
+	}
+
+	print '</tr>'."\n";
+
+	//affichage des horaires
+	if (strpos($object->sujet, '@') !== false) {
+		print '<tr>'."\n";
+		print '<td></td>'."\n";
+
+		for ($i=0; isset($toutsujet[$i]); $i++) {
+			$heures=explode('@',$toutsujet[$i]);
+			if (isset($heures[1])) {
+				print '<td class="heure">'.$heures[1].'</td>'."\n";
+			} else {
+				print '<td class="heure"></td>'."\n";
+			}
+		}
+
+		print '</tr>'."\n";
+	}
+}
+else
+{
+	$toutsujet=str_replace("°","'",$toutsujet);
+
+	//affichage des sujets du sondage
+	print '<tr>'."\n";
+	print '<td></td>'."\n";
+
+	for ($i=0; isset($toutsujet[$i]); $i++)
+	{
+		$tmp=explode('@',$toutsujet[$i]);
+		print '<td class="sujet">'.$tmp[0].'</td>'."\n";
+	}
+
+	print '</tr>'."\n";
+}
+
+
+// Loop on each answer
+$sumfor = array();
+$sumagainst = array();
+$compteur = 0;
+
+$sql = 'SELECT * FROM '.MAIN_DB_PREFIX.'opensurvey_user_studs WHERE id_sondage='.$connect->Param('numsondage').' ORDER BY id_users';
+$sql = $connect->Prepare($sql);
+$user_studs = $connect->Execute($sql, array($numsondage));
+
+while ($data = $user_studs->FetchNextObject(false))
+{
+	$ensemblereponses = $data->reponses;
+	$nombase=str_replace("°","'",$data->nom);
+
+	print '<tr>'."\n";
+
+	// ligne d'un usager pré-authentifié
+	$mod_ok = ($object->canedit || (! empty($nombase) && in_array($nombase, $listofvoters)));
+
+	// Name
+	print '<td class="nom">'.$nombase.'</td>'."\n";
+
+	// pour chaque colonne
+	for ($i=0; $i < $nbcolonnes; $i++)
+	{
+		$car = substr($ensemblereponses, $i, 1);
+		if ($compteur == $ligneamodifier)
+		{
+			print '<td class="vide">';
+			if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+			{
+				print '<input type="checkbox" name="choix'.$i.'" value="1" ';
+				if (((string) $car) == '1') print 'checked="checked"';
+				print '>';
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+			{
+				$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes"));
+				print $form->selectarray("choix".$i, $arraychoice, $car);
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+			{
+				$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("Against"),'1'=>$langs->trans("For"));
+				print $form->selectarray("choix".$i, $arraychoice, $car);
+			}
+			print '</td>'."\n";
+		}
+		else
+		{
+			if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+			{
+				if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n";
+				else print '<td class="non">KO</td>'."\n";
+				// Total
+				if (isset($sumfor[$i]) === false) $sumfor[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+			{
+				if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n";
+				else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n";
+				else print '<td class="vide">&nbsp;</td>'."\n";
+				// Total
+				if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+				if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+				if (((string) $car) == "0") $sumagainst[$i]++;
+			}
+			if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+			{
+				if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
+				else if (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
+				else print '<td class="vide">&nbsp;</td>'."\n";
+				// Total
+				if (! isset($sumfor[$i])) $sumfor[$i] = 0;
+				if (! isset($sumagainst[$i])) $sumagainst[$i] = 0;
+				if (((string) $car) == "1") $sumfor[$i]++;
+				if (((string) $car) == "0") $sumagainst[$i]++;
+			}
+		}
+	}
+
+	//  Button edit at end of line
+	if ($compteur != $ligneamodifier && $mod_ok)
+	{
+		print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n";
+	}
+
+	//demande de confirmation pour modification de ligne
+	for ($i=0;$i<$nblignes;$i++) {
+		if (isset($_POST["modifierligne$i"])) {
+			if ($compteur == $i) {
+				print '<td class="casevide"><input type="submit" class="button" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'"></td>'."\n";
+			}
+		}
+	}
+
+	$compteur++;
+	print '</tr>'."\n";
+}
+
+// Add line to add new record
+if ($ligneamodifier < 0 && (! isset($_SESSION['nom'])))
+{
+	print '<tr>'."\n";
+	print '<td class="nom">'."\n";
+	if (isset($_SESSION['nom']))
+	{
+		print '<input type=hidden name="nom" value="'.$_SESSION['nom'].'">'.$_SESSION['nom']."\n";
+	} else {
+		print '<input type="text" name="nom" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" maxlength="64" size="24">'."\n";
+	}
+	print '</td>'."\n";
+
+	// affichage des cases de formulaire checkbox pour un nouveau choix
+	for ($i=0;$i<$nbcolonnes;$i++)
+	{
+		print '<td class="vide">';
+		if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst')))
+		{
+			print '<input type="checkbox" name="choix'.$i.'" value="1"';
+			if (isset($_POST['choix'.$i]) && $_POST['choix'.$i] == '1' && is_error(NAME_EMPTY) )
+			{
+				print ' checked="checked"';
+			}
+			print '>';
+		}
+		if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno')
+		{
+			$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("No"),'1'=>$langs->trans("Yes"));
+			print $form->selectarray("choix".$i, $arraychoice, GETPOST('choix'.$i));
+		}
+		if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst')
+		{
+			$arraychoice=array('2'=>'&nbsp;','0'=>$langs->trans("Against"),'1'=>$langs->trans("For"));
+			print $form->selectarray("choix".$i, $arraychoice, GETPOST('choix'.$i));
+		}
+		print '</td>'."\n";
+	}
+
+	// Affichage du bouton de formulaire pour inscrire un nouvel utilisateur dans la base
+	print '<td><input type="image" name="boutonp" value="' . $langs->trans('Vote') . '" src="'.dol_buildpath('/opensurvey/img/add-24.png',1).'"></td>'."\n";
+	print '</tr>'."\n";
+}
+
+// Select value of best choice (for checkbox columns only)
+$nbofcheckbox=0;
+for ($i=0; $i < $nbcolonnes; $i++)
+{
+	if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] != 'checkbox') continue;
+	$nbofcheckbox++;
+	if (isset($sumfor[$i]))
+	{
+		if ($i == 0)
+		{
+			$meilleurecolonne = $sumfor[$i];
+		}
+		if (! isset($meilleurecolonne) || $sumfor[$i] > $meilleurecolonne)
+		{
+			$meilleurecolonne = $sumfor[$i];
+		}
+	}
+}
+
+// Show line total
+print '<tr '.$bc[false].'>'."\n";
+print '<td align="center">'. $langs->trans("Total") .'</td>'."\n";
+for ($i = 0; $i < $nbcolonnes; $i++)
+{
+	$showsumfor = isset($sumfor[$i])?$sumfor[$i]:'';
+	$showsumagainst = isset($sumagainst[$i])?$sumagainst[$i]:'';
+	if (empty($showsumfor)) $showsumfor = 0;
+	if (empty($showsumagainst)) $showsumagainst = 0;
+
+	print '<td>';
+	if (empty($listofanswers[$i]['format']) || ! in_array($listofanswers[$i]['format'],array('yesno','foragainst'))) print $showsumfor;
+	if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst;
+	if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst;
+	print '</td>'."\n";
+}
+print '</tr>';
+// Show picto winnner
+if ($nbofcheckbox >= 2)
+{
+	print '<tr>'."\n";
+	print '<td class="somme"></td>'."\n";
+	for ($i=0; $i < $nbcolonnes; $i++)
+	{
+		//print 'xx'.(! empty($listofanswers[$i]['format'])).'-'.$sumfor[$i].'-'.$meilleurecolonne;
+		if (! empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'checkbox' && isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne)
+		{
+			print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png',1).'"></td>'."\n";
+		} else {
+			print '<td class="somme"></td>'."\n";
+		}
+	}
+	print '</tr>'."\n";
+}
+print '</table>'."\n";
+print '</div>'."\n";
+
+$toutsujet=explode(",",$object->sujet);
+$toutsujet=str_replace("°","'",$toutsujet);
+
+$compteursujet=0;
+$meilleursujet = '';
+
+for ($i = 0; $i < $nbcolonnes; $i++) {
+	if (isset($sumfor[$i]) && isset($meilleurecolonne) && $sumfor[$i] == $meilleurecolonne) {
+		$meilleursujet.=", ";
+		if ($object->format=="D"||$object->format=="D+") {
+			$meilleursujetexport = $toutsujet[$i];
+
+			if (strpos($toutsujet[$i], '@') !== false) {
+				$toutsujetdate = explode("@", $toutsujet[$i]);
+				$meilleursujet .= dol_print_date($toutsujetdate[0],'daytext'). ' ('.dol_print_date($toutsujetdate[0],'%A').')' . _("for")  . ' ' . $toutsujetdate[1];
+			} else {
+				$meilleursujet .= dol_print_date($toutsujet[$i],'daytext'). ' ('.dol_print_date($toutsujet[$i],'%A').')';
+			}
+		} else {
+			$tmps=explode('@',$toutsujet[$i]);
+			$meilleursujet .= $tmps[0];
+		}
+
+		$compteursujet++;
+	}
+}
+
+$meilleursujet=substr("$meilleursujet", 1);
+$meilleursujet = str_replace("°", "'", $meilleursujet);
+
+
+// Show best choice
+if ($nbofcheckbox >= 2)
+{
+	$vote_str = $langs->trans('votes');
+	print '<p class="affichageresultats">'."\n";
+
+	if ($compteursujet == "1" && isset($meilleurecolonne)) {
+		print '<img src="images/medaille.png" alt="Meilleur choix"> ' . $langs->trans('TheBestChoice') . ": <b>$meilleursujet</b> " . $langs->trans('with') . " <b>$meilleurecolonne </b>" . $vote_str . ".\n";
+	} elseif (isset($meilleurecolonne)) {
+		print '<img src="images/medaille.png" alt="Meilleur choix"> ' . $langs->trans('TheBestChoices')  . ": <b>$meilleursujet</b> " . $langs->trans('with') . "  <b>$meilleurecolonne </b>" . $vote_str . ".\n";
+	}
+
+	print '</p><br>';
+}
+
+print '<br>';
+
+
+// Comment list
+$sql = 'SELECT id_comment, usercomment, comment';
+$sql.= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments';
+$sql.= " WHERE id_sondage='".$db->escape($numsondage)."'";
+$sql.= " ORDER BY id_comment";
+$resql = $db->query($sql);
+$num_rows=$db->num_rows($resql);
+if ($num_rows > 0)
+{
+	$i = 0;
+	print "<br><b>" . $langs->trans("CommentsOfVoters") . " :</b><br>\n";
+	while ( $i < $num_rows)
+	{
+		$obj=$db->fetch_object($resql);
+		print '<div class="comment"><span class="usercomment">';
+		if (in_array($obj->usercomment, $listofvoters)) print '<a href="'.$_SERVER["PHP_SELF"].'?deletecomment='.$obj->id_comment.'&sondage='.$numsondage.'"> '.img_picto('', 'delete.png').'</a> ';
+		print $obj->usercomment.' :</span> <span class="comment">'.dol_nl2br($obj->comment)."</span></div>";
+		$i++;
+	}
+}
+
+// Form to add comment
+print '<div class="addcomment">' .$langs->trans("AddACommentForPoll") . "<br>\n";
+
+print '<textarea name="comment" rows="2" cols="60"></textarea><br>'."\n";
+print $langs->trans("Name") .' : ';
+print '<input type="text" name="commentuser" maxlength="64" /> &nbsp; '."\n";
+print '<input type="submit" class="button" name="ajoutcomment" value="'.dol_escape_htmltag($langs->trans("AddComment")).'"><br>'."\n";
+print '</form>'."\n";
+// Focus javascript sur la case de texte du formulaire
+print '</div>'."\n";
+
+print '<br><br>';
+
+/*
+// Define $urlwithroot
+$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+$message='';
+$url=$urlwithouturlroot.dol_buildpath('/opensurvey/public/studs.php',1).'?sondage='.$numsondage;
+$urlvcal='<a href="'.$url.'" target="_blank">'.$url.'</a>';
+$message.=img_picto('','object_globe.png').' '.$langs->trans("UrlForSurvey").': '.$urlvcal;
+
+print '<center>'.$message.'</center>';
+*/
+
+
+print '<a name="bas"></a>'."\n";
+
+llxFooterSurvey();
+
+$db->close();
+?>
\ No newline at end of file
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_comments.key.sql b/htdocs/opensurvey/sql/llx_opensurvey_comments.key.sql
new file mode 100755
index 0000000000000000000000000000000000000000..3f7460f3e8aa9431eaddd76611d8dd34c38cf79d
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_comments.key.sql
@@ -0,0 +1,22 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+ALTER TABLE llx_opensurvey_comments ADD INDEX idx_id_comment id_comment;
+ALTER TABLE llx_opensurvey_comments ADD INDEX idx_id_sondage id_sondage;
+
+
+
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_comments.sql b/htdocs/opensurvey/sql/llx_opensurvey_comments.sql
new file mode 100755
index 0000000000000000000000000000000000000000..613627c46aa6fa5c23a7fc2b10065ae23809a33b
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_comments.sql
@@ -0,0 +1,25 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+CREATE TABLE llx_opensurvey_comments (
+    id_comment INTEGER unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
+    id_sondage CHAR(16) NOT NULL,
+    comment text NOT NULL,
+    tms timestamp,
+    usercomment text
+) ENGINE=InnoDB;
+
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_sondage.key.sql b/htdocs/opensurvey/sql/llx_opensurvey_sondage.key.sql
new file mode 100755
index 0000000000000000000000000000000000000000..377f8abc45e6e2d0a9f7ec5f52118a27d21f70c9
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_sondage.key.sql
@@ -0,0 +1,19 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+ALTER TABLE llx_opensurvey_sondage ADD INDEX idx_id_sondage_admin id_sondage_admin;
+ALTER TABLE llx_opensurvey_sondage ADD INDEX idx_date_fin date_fin;
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_sondage.sql b/htdocs/opensurvey/sql/llx_opensurvey_sondage.sql
new file mode 100755
index 0000000000000000000000000000000000000000..1704938a6f788b5eef3685ce9fac03feeb493d93
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_sondage.sql
@@ -0,0 +1,33 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+CREATE TABLE llx_opensurvey_sondage (
+       id_sondage VARCHAR(16) PRIMARY KEY,
+       id_sondage_admin CHAR(24),
+       commentaires text,
+       mail_admin VARCHAR(128),
+       nom_admin VARCHAR(64),
+       titre text,
+       date_fin datetime,
+       format VARCHAR(2),
+       mailsonde varchar(2) DEFAULT '0',
+       survey_link_visible integer DEFAULT 1,
+	   canedit integer DEFAULT 0,
+       origin varchar(64),
+       tms timestamp,
+	   sujet TEXT
+) ENGINE=InnoDB;
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_user_studs.key.sql b/htdocs/opensurvey/sql/llx_opensurvey_user_studs.key.sql
new file mode 100755
index 0000000000000000000000000000000000000000..041b2d0593d458580b714531705ca4f3aaa56cd4
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_user_studs.key.sql
@@ -0,0 +1,20 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+ALTER TABLE llx_opensurvey_user_studs ADD INDEX idx_id_users (id_users);
+ALTER TABLE llx_opensurvey_user_studs ADD INDEX idx_nom (nom);
+ALTER TABLE llx_opensurvey_user_studs ADD INDEX idx_id_sondage (id_sondage);
diff --git a/htdocs/opensurvey/sql/llx_opensurvey_user_studs.sql b/htdocs/opensurvey/sql/llx_opensurvey_user_studs.sql
new file mode 100755
index 0000000000000000000000000000000000000000..78d7fa69c4d9626a164793e425e3798d44e52c90
--- /dev/null
+++ b/htdocs/opensurvey/sql/llx_opensurvey_user_studs.sql
@@ -0,0 +1,24 @@
+-- ============================================================================
+-- Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
+--
+-- 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
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- ============================================================================
+
+CREATE TABLE llx_opensurvey_user_studs (
+    id_users INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
+    nom VARCHAR(64) NOT NULL,
+    id_sondage VARCHAR(16) NOT NULL,
+    reponses VARCHAR(100) NOT NULL,
+    tms timestamp
+) ENGINE=InnoDB;
diff --git a/htdocs/product/fiche.php b/htdocs/product/fiche.php
index 60c3785751ffcb44ae858235fdd81b3d5b8cfb11..e8775f4462137492ef3b7167f824845aff8e24a0 100644
--- a/htdocs/product/fiche.php
+++ b/htdocs/product/fiche.php
@@ -638,11 +638,17 @@ $formproduct = new FormProduct($db);
 
 if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
 {
-    // -----------------------------------------
-    // When used with CANVAS (more simple)
-    // -----------------------------------------
-    $objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
-    $objcanvas->display_canvas($action);							// Show template
+	// -----------------------------------------
+	// When used with CANVAS
+	// -----------------------------------------
+	if (empty($object->error) && $id)
+	{
+		$object = new Product($db);
+		$result=$object->fetch($id);
+		if ($result <= 0) dol_print_error('',$object->error);
+	}
+	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
+	$objcanvas->display_canvas($action);							// Show template
 }
 else
 {
diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php
index d2864b08c1121001d72a5f170335e3ed0ae3864a..b02b29eaa69674ae55f01176adde9284a9804c91 100644
--- a/htdocs/projet/class/project.class.php
+++ b/htdocs/projet/class/project.class.php
@@ -1011,7 +1011,7 @@ class Project extends CommonObject
         	else
         	{
         		$this->db->begin();
-				$res=$clone_project->update_note_public(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES));
+				$res=$clone_project->update_note(dol_html_entity_decode($clone_project->note_public, ENT_QUOTES),'_public');
 				if ($res < 0)
 				{
 					$this->error.=$clone_project->error;
diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php
index f28e5d27e6d3f629a91b7268b05d52d9de09c6c8..d09647347e5e0d815ff38da088792d7b2b2315e7 100644
--- a/htdocs/projet/class/task.class.php
+++ b/htdocs/projet/class/task.class.php
@@ -1027,7 +1027,7 @@ class Task extends CommonObject
         	else
         	{
         		$this->db->begin();
-				$res=$clone_task->update_note_public(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES));
+				$res=$clone_task->update_note(dol_html_entity_decode($clone_task->note_public, ENT_QUOTES),'_public');
 				if ($res < 0)
 				{
 					$this->error.=$clone_task->error;
diff --git a/htdocs/projet/note.php b/htdocs/projet/note.php
index e785cf778ab2fd1d5ee0519c22bc2e132b020ff1..26eafbc16d22136f3dcbd6292d4d5c39e992e17c 100644
--- a/htdocs/projet/note.php
+++ b/htdocs/projet/note.php
@@ -56,7 +56,7 @@ $result = restrictedArea($user, 'projet', $id);
 if ($action == 'setnote_public' && $user->rights->projet->creer)
 {
 	$object->fetch($id);
-	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
 	if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/projet/tasks/note.php b/htdocs/projet/tasks/note.php
index 6d5f9f666e945e94005d57c6506d480aa3c2e814..9931bde05103b2c8198b6e2cdb7b642a91ead7a4 100644
--- a/htdocs/projet/tasks/note.php
+++ b/htdocs/projet/tasks/note.php
@@ -87,7 +87,7 @@ $permission=($user->rights->projet->creer || $user->rights->projet->all->creer);
 
 if ($action == 'setnote_public' && ! empty($permission))
 {
-    $result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
+    $result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
     if ($result < 0) dol_print_error($db,$object->error);
 }
 
diff --git a/htdocs/public/paybox/paymentko.php b/htdocs/public/paybox/paymentko.php
index 4db0684005bf0c7e555d6a7c2316346dcd08613f..ae3dcf3e4e0d76e679be1739417417b800b78c8b 100644
--- a/htdocs/public/paybox/paymentko.php
+++ b/htdocs/public/paybox/paymentko.php
@@ -69,13 +69,12 @@ if (! empty($conf->global->MEMBER_PAYONLINE_SENDEMAIL) && preg_match('/MEM=',$fu
 	$sendto=$conf->global->MEMBER_PAYONLINE_SENDEMAIL;
 	$from=$conf->global->MAILING_EMAIL_FROM;
 	require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-	$mailfile = new CMailFile(
+	$mailfile = new CMailFile(
 		'New subscription payed',
 		$sendto,
-		$from,
-		'New subscription payed '.$fulltag
-	);
-
+		$from,
+		'New subscription payed '.$fulltag);
+
 	$result=$mailfile->sendfile();
 	if ($result)
 	{
diff --git a/htdocs/public/paybox/paymentok.php b/htdocs/public/paybox/paymentok.php
index ebd3c834d09e29ecf3c466a87dd27a2cf2c744c3..25a64bda85a0529cd082d03f200d4715b39c8a8a 100644
--- a/htdocs/public/paybox/paymentok.php
+++ b/htdocs/public/paybox/paymentok.php
@@ -99,12 +99,11 @@ if (! empty($conf->global->MEMBER_PAYONLINE_SENDEMAIL) && preg_match('/MEM=',$fu
 	$sendto=$conf->global->MEMBER_PAYONLINE_SENDEMAIL;
 	$from=$conf->global->MAILING_EMAIL_FROM;
 	require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-	$mailfile = new CMailFile(
+	$mailfile = new CMailFile(
 		'New subscription payed',
 		$sendto,
 		$from,
-		'New subscription payed '.$fulltag
-	);
+		'New subscription payed '.$fulltag);
 
 	$result=$mailfile->sendfile();
 	if ($result)
diff --git a/htdocs/public/paypal/paymentko.php b/htdocs/public/paypal/paymentko.php
index c6fe53ac7b06d80aa1ec38e7517a391fe3ceae5f..1ba3608eb87c5ca41276fb51d0261bde11f90f14 100755
--- a/htdocs/public/paypal/paymentko.php
+++ b/htdocs/public/paypal/paymentko.php
@@ -77,12 +77,11 @@ if (! empty($conf->global->MEMBER_PAYONLINE_SENDEMAIL) && preg_match('/MEM=',$fu
 	$sendto=$conf->global->MEMBER_PAYONLINE_SENDEMAIL;
 	$from=$conf->global->MAILING_EMAIL_FROM;
 	require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-	$mailfile = new CMailFile(
+	$mailfile = new CMailFile(
 		'New subscription payed',
 		$sendto,
 		$from,
-		'New subscription payed '.$fulltag
-	);
+		'New subscription payed '.$fulltag);
 
 	$result=$mailfile->sendfile();
 	if ($result)
diff --git a/htdocs/public/paypal/paymentok.php b/htdocs/public/paypal/paymentok.php
index ca11bcb54226d99afd37558dfb664e5fc6e594c8..27755754a03dddb20bade8f6e0b3bd69e748f6b5 100755
--- a/htdocs/public/paypal/paymentok.php
+++ b/htdocs/public/paypal/paymentok.php
@@ -136,12 +136,11 @@ if ($PAYPALTOKEN)
 		$sendto=$conf->global->MEMBER_PAYONLINE_SENDEMAIL;
 		$from=$conf->global->MAILING_EMAIL_FROM;
 		require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-		$mailfile = new CMailFile(
+		$mailfile = new CMailFile(
 			'New subscription payed',
 			$sendto,
 			$from,
-			'New subscription payed '.$fulltag
-		);
+			'New subscription payed '.$fulltag);
 
 		$result=$mailfile->sendfile();
 		if ($result)
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 97291206ad4df4eb14593156ef8a14b64ef2ac41..da5927128ae093bf9c05ac96aaddaf654fc91300 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -7,6 +7,7 @@
  * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2008      Patrick Raguin       <patrick.raguin@auguria.net>
  * Copyright (C) 2010-2011 Juanjo Menent        <jmenent@2byte.es>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -118,7 +119,9 @@ class Societe extends CommonObject
     var $code_compta;
     var $code_compta_fournisseur;
 
-    var $note;
+    var $note; //TODO deprecated
+    var $note_private;
+    var $note_public;
     //! code statut prospect
     var $stcomm_id;
     var $statut_commercial;
@@ -698,7 +701,7 @@ class Societe extends CommonObject
         $sql .= ', s.status';
         $sql .= ', s.price_level';
         $sql .= ', s.tms as date_update';
-        $sql .= ', s.phone, s.fax, s.email, s.url, s.zip, s.town, s.note, s.client, s.fournisseur';
+        $sql .= ', s.phone, s.fax, s.email, s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
         $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
         $sql .= ', s.capital, s.tva_intra';
         $sql .= ', s.fk_typent as typent_id';
@@ -832,7 +835,9 @@ class Societe extends CommonObject
                 $this->client      = $obj->client;
                 $this->fournisseur = $obj->fournisseur;
 
-                $this->note = $obj->note;
+                $this->note = $obj->note_private; //TODO Deprecatedfor backward comtability
+                $this->note_private = $obj->note_private;
+                $this->note_public = $obj->note_public;
                 $this->default_lang = $obj->default_lang;
                 $this->logo = $obj->logo;
 
@@ -2444,7 +2449,7 @@ class Societe extends CommonObject
     	$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
     	$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
     	$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_DEPARTEMENT)?'':$conf->global->MAIN_INFO_SOCIETE_DEPARTEMENT;
-    	$this->note=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
+    	$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
 
     	$this->nom=$this->name; 									// deprecated
 
@@ -2541,7 +2546,7 @@ class Societe extends CommonObject
         $this->tva_assuj=1;
         $this->tva_intra='EU1234567';
         $this->note_public='This is a comment (public)';
-        $this->note='This is a comment (private)';
+        $this->note_private='This is a comment (private)';
 
         $this->idprof1='idprof1';
         $this->idprof2='idprof2';
diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php
index f3538c6e266a7fd27c76dd0d175da54bd3192651..7c0a4c0332f251408d02d5e7d868867fc03e57d6 100644
--- a/htdocs/societe/consumption.php
+++ b/htdocs/societe/consumption.php
@@ -106,7 +106,7 @@ print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" name="socid" value="'.$socid.'">';
 
 print '<table class="border" width="100%">';
-print '<tr><td width="30%">'.$langs->trans('ThirdPartyName').'</td>';
+print '<tr><td width="25%">'.$langs->trans('ThirdPartyName').'</td>';
 print '<td colspan="3">';
 print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom');
 print '</td></tr>';
diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php
index ca5582b4deed019b249ad717ebc1410776c773da..f97030442573381fa1b8f06b1ccbc239da422889 100644
--- a/htdocs/societe/document.php
+++ b/htdocs/societe/document.php
@@ -133,7 +133,7 @@ if ($object->id)
 	print '<table class="border"width="100%">';
 
 	// Ref
-	print '<tr><td width="30%">'.$langs->trans("ThirdPartyName").'</td>';
+	print '<tr><td width="25%">'.$langs->trans("ThirdPartyName").'</td>';
 	print '<td colspan="3">';
 	print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom');
 	print '</td></tr>';
diff --git a/htdocs/societe/note.php b/htdocs/societe/note.php
index 01a43230f7fa01a29ea0a3ae7c0f6027a024c8f1..8fbd6c6187f91bd12e4e14982db70cf8b9ca512d 100644
--- a/htdocs/societe/note.php
+++ b/htdocs/societe/note.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2011      Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2012      Regis Houssin        <regis.houssin@capnetworks.com>
  * Copyright (C) 2010           Juanjo Menent        <jmenent@2byte.es>
+ * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  *
  * 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
@@ -24,6 +25,10 @@
  *   \ingroup    societe
  */
 
+error_reporting(E_ALL);
+ini_set('display_errors', true);
+ini_set('html_errors', false);
+
 require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
 
@@ -32,39 +37,45 @@ $action = GETPOST('action');
 $langs->load("companies");
 
 // Security check
-$socid = GETPOST('socid','int');
-if ($user->societe_id) $socid=$user->societe_id;
-$result = restrictedArea($user, 'societe', $socid, '&societe');
+$id = GETPOST('id','int');
+if ($user->societe_id) $id=$user->societe_id;
+$result = restrictedArea($user, 'societe', $id, '&societe');
 
 $object = new Societe($db);
-if ($socid > 0) $object->fetch($socid);
+if ($id > 0) $object->fetch($id);
 
 /*
  * Actions
  */
 
-if ($action == 'add' && ! GETPOST('cancel'))
+/******************************************************************************/
+/*                     Actions                                                */
+/******************************************************************************/
+
+if ($action == 'setnote_public' && $user->rights->propale->creer)
 {
-    $result=$object->update_note($_POST["note"]);
-    if ($result < 0)
-    {
-         $errors[]=$object->errors;
-    }
+	$object->fetch($id);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES),'_public');
+	if ($result < 0) setEventMessage($object->error,'errors');
 }
 
+else if ($action == 'setnote_private' && $user->rights->propale->creer)
+{
+	$object->fetch($id);
+	$result=$object->update_note(dol_html_entity_decode(GETPOST('note_private'), ENT_QUOTES),'_private');
+	if ($result < 0) setEventMessage($object->error,'errors');
+}
 
 /*
  *	View
  */
 
-if ($conf->global->MAIN_DIRECTEDITMODE && $user->rights->societe->creer) $action='edit';
-
 $form = new Form($db);
 
 $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('',$langs->trans("ThirdParty").' - '.$langs->trans("Notes"),$help_url);
 
-if ($socid > 0)
+if ($id > 0)
 {
     /*
      * Affichage onglets
@@ -73,7 +84,6 @@ if ($socid > 0)
 
     $head = societe_prepare_head($object);
 
-
     dol_fiche_head($head, 'note', $langs->trans("ThirdParty"),0,'company');
 
 
@@ -82,7 +92,7 @@ if ($socid > 0)
 
     print '<table class="border" width="100%">';
 
-    print '<tr><td width="20%">'.$langs->trans('ThirdPartyName').'</td>';
+    print '<tr><td width="25%">'.$langs->trans('ThirdPartyName').'</td>';
     print '<td colspan="3">';
     print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom');
     print '</td></tr>';
@@ -110,61 +120,18 @@ if ($socid > 0)
         print '</td></tr>';
     }
 
-    print '<tr><td valign="top">'.$langs->trans("Note").'</td>';
-    print '<td valign="top">';
-    if ($action == 'edit' && $user->rights->societe->creer)
-    {
-        print '<input type="hidden" name="action" value="add" />';
-        print '<input type="hidden" name="socid" value="'.$object->id.'" />';
-
-        // Editeur wysiwyg
-        require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-        $doleditor=new DolEditor('note',$object->note,'',360,'dolibarr_notes','In',true,false,$conf->global->FCKEDITOR_ENABLE_SOCIETE,20,70);
-        $doleditor->Create();
-    }
-    else
-    {
-        print dol_textishtml($object->note)?$object->note:dol_nl2br($object->note,1,true);
-    }
-    print "</td></tr>";
-
     print "</table>";
 
-    if ($action == 'edit')
-    {
-        print '<center><br>';
-        print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
-        print ' &nbsp; ';
-        print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
-        print '</center>';
-    }
-
-    print '</form>';
-
-    dol_fiche_end();
-}
-
-dol_htmloutput_errors('',$errors);
+    print '<br>';
 
+    $colwidth='25';
+    include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
-/*
- * Buttons
- */
 
-if ($action != 'edit')
-{
-    print '<div class="tabsAction">';
-
-    if ($user->rights->societe->creer)
-    {
-        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>';
-    }
-
-    print '</div>';
+    dol_fiche_end();
 }
 
 llxFooter();
-
 $db->close();
 
-?>
+?>
\ No newline at end of file
diff --git a/htdocs/societe/notify/fiche.php b/htdocs/societe/notify/fiche.php
index 2499ae30a5b9f65ec6d21ff99b8497958c9de168..a0ab078e315ae76aef0b88d7c89c767580002e5b 100644
--- a/htdocs/societe/notify/fiche.php
+++ b/htdocs/societe/notify/fiche.php
@@ -141,7 +141,7 @@ if ($result > 0)
 
     print '<table class="border"width="100%">';
 
-    print '<tr><td width="20%">'.$langs->trans("ThirdPartyName").'</td><td colspan="3">';
+    print '<tr><td width="25%">'.$langs->trans("ThirdPartyName").'</td><td colspan="3">';
     print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom');
     print '</td></tr>';
 
@@ -169,7 +169,7 @@ if ($result > 0)
         print '</td></tr>';
     }
 
-    print '<tr><td width="30%">'.$langs->trans("NbOfActiveNotifications").'</td>';
+    print '<tr><td>'.$langs->trans("NbOfActiveNotifications").'</td>';
     print '<td colspan="3">';
     $sql = "SELECT COUNT(n.rowid) as nb";
     $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n";
diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php
index 772e1b2449754479b5f76ba635c0c18875b038f7..0ee8d7d0f8cdc41d3cf34be5f8dcdd119c075c97 100644
--- a/htdocs/societe/soc.php
+++ b/htdocs/societe/soc.php
@@ -528,10 +528,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
     if (empty($object->error) && $socid)
  	{
 	     $object = new Societe($db);
-	     $object->fetch($socid);
+	     $result=$object->fetch($socid);
+	     if ($result <= 0) dol_print_error('',$object->error);
  	}
-   	$objcanvas->assign_values($action, $socid);	// Set value for templates
-    $objcanvas->display_canvas($action);		// Show template
+   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
+    $objcanvas->display_canvas($action);							// Show template
 }
 else
 {
@@ -1464,7 +1465,7 @@ else
         */
 
         // Name
-        print '<tr><td width="20%">'.$langs->trans('ThirdPartyName').'</td>';
+        print '<tr><td width="25%">'.$langs->trans('ThirdPartyName').'</td>';
         print '<td colspan="3">';
         print $form->showrefnav($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom');
         print '</td>';
diff --git a/htdocs/theme/amarok/style.css.php b/htdocs/theme/amarok/style.css.php
index a2b4b6ef7d5af9cc9c67a1e722c269f45074fb5a..0d913e037fa74ca65594faae9ac170ff4974e9d2 100755
--- a/htdocs/theme/amarok/style.css.php
+++ b/htdocs/theme/amarok/style.css.php
@@ -174,6 +174,7 @@ select.flat {
 	border-top:solid 1px rgba(0,0,0,.4);
 	border-bottom:solid 1px rgba(0,0,0,.2);
 	box-shadow:1px 1px 2px rgba(0,0,0,.2) inset;
+	background: #FDFDFD;
 }
 
 form {
diff --git a/htdocs/theme/eldy/graph-color.php b/htdocs/theme/eldy/graph-color.php
index e49f86bce60175f57941828430019107767a5a10..ab59c7689a44fff4b4b57927244ad1877fae4f5d 100644
--- a/htdocs/theme/eldy/graph-color.php
+++ b/htdocs/theme/eldy/graph-color.php
@@ -28,7 +28,7 @@
 
 global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet;
 $theme_bordercolor = array(235,235,224);
-$theme_datacolor = array(array(125,135,150), array(200,160,180), array(190,190,220), array(170,140,190), array(190,190,170));
+$theme_datacolor = array(array(190,190,220), array(200,160,180), array(125,135,150), array(170,140,190), array(190,190,170));
 $theme_bgcolor = array(hexdec('F4'),hexdec('F4'),hexdec('F4'));
 $theme_bgcoloronglet = array(hexdec('DE'),hexdec('E7'),hexdec('EC'));
 
diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php
index a2eb25bf01f91af9f67a10265dbe53dd0e317120..79d4c17be7ebf8572d43a0cda04f9a50421f989a 100644
--- a/htdocs/theme/eldy/style.css.php
+++ b/htdocs/theme/eldy/style.css.php
@@ -2101,7 +2101,7 @@ table.cal_month    { border-spacing: 0px; }
 .cal_other_month   { border-top: 0; border-left: solid 1px #C0C0C0; border-right: 0; border-bottom: solid 1px #C0C0C0; }
 .cal_current_month_right { border-right: solid 1px #E0E0E0; }
 .cal_other_month_right   { border-right: solid 1px #C0C0C0; }
-.cal_other_month   { opacity: 0.6; background: #DDDDDD; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
+.cal_other_month   { opacity: 0.6; background: #EAEAEA; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
 .cal_past_month    { opacity: 0.6; background: #EEEEEE; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
 .cal_current_month { background: #FFFFFF; border-left: solid 1px #E0E0E0; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
 .cal_today         { background: #FFFFFF; border: solid 2px #6C7C7B; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php
index 7088376960286d882689ff5b6dc95e3120289cd6..0d50e08e0fdfddbb383f1cfd0fc85bcdbef02052 100644
--- a/htdocs/user/class/user.class.php
+++ b/htdocs/user/class/user.class.php
@@ -76,11 +76,6 @@ class User extends CommonObject
 	var $fk_member;
 	var $fk_user;
 
-	var $webcal_login;
-	var $phenix_login;
-	var $phenix_pass;
-	var $phenix_pass_crypted;
-
 	var $clicktodial_url;
 	var $clicktodial_login;
 	var $clicktodial_password;
@@ -144,7 +139,7 @@ class User extends CommonObject
 
 		// Get user
 		$sql = "SELECT u.rowid, u.lastname, u.firstname, u.email, u.job, u.signature, u.office_phone, u.office_fax, u.user_mobile,";
-		$sql.= " u.admin, u.login, u.webcal_login, u.phenix_login, u.phenix_pass, u.note,";
+		$sql.= " u.admin, u.login, u.note,";
 		$sql.= " u.pass, u.pass_crypted, u.pass_temp,";
 		$sql.= " u.fk_societe, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid,";
 		$sql.= " u.statut, u.lang, u.entity,";
@@ -220,9 +215,6 @@ class User extends CommonObject
 				$this->datelastlogin		= $this->db->jdate($obj->datel);
 				$this->datepreviouslogin	= $this->db->jdate($obj->datep);
 
-				$this->webcal_login         = $obj->webcal_login;
-				$this->phenix_login         = $obj->phenix_login;
-				$this->phenix_pass_crypted  = $obj->phenix_pass;
 				$this->societe_id           = $obj->fk_societe;
 				$this->contact_id           = $obj->fk_socpeople;
 				$this->fk_member            = $obj->fk_member;
@@ -1111,12 +1103,6 @@ class User extends CommonObject
 		$this->signature    = trim($this->signature);
 		$this->note         = trim($this->note);
 		$this->openid       = trim(empty($this->openid)?'':$this->openid);    // Avoid warning
-		$this->webcal_login = trim($this->webcal_login);
-		$this->phenix_login = trim($this->phenix_login);
-		if ($this->phenix_pass != $this->phenix_pass_crypted)
-		{
-			$this->phenix_pass  = dol_hash(trim($this->phenix_pass));
-		}
 		$this->admin        = $this->admin?$this->admin:0;
 
 		// Check parameters
@@ -1146,9 +1132,6 @@ class User extends CommonObject
 		$sql.= ", email = '".$this->db->escape($this->email)."'";
 		$sql.= ", job = '".$this->db->escape($this->job)."'";
 		$sql.= ", signature = '".$this->db->escape($this->signature)."'";
-		$sql.= ", webcal_login = '".$this->db->escape($this->webcal_login)."'";
-		$sql.= ", phenix_login = '".$this->db->escape($this->phenix_login)."'";
-		$sql.= ", phenix_pass = '".$this->db->escape($this->phenix_pass)."'";
 		$sql.= ", note = '".$this->db->escape($this->note)."'";
 		$sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null");
 		$sql.= ", openid = ".($this->openid?"'".$this->db->escape($this->openid)."'":"null");
@@ -1954,6 +1937,8 @@ class User extends CommonObject
 	{
 		global $user,$langs;
 
+		$now=dol_now();
+		
 		// Initialise parametres
 		$this->id=0;
 		$this->ref = 'SPECIMEN';
@@ -1971,12 +1956,11 @@ class User extends CommonObject
 		$this->pass='dolibspec';
 		//$this->pass_indatabase='dolibspec';									Set after a fetch
 		//$this->pass_indatabase_crypted='e80ca5a88c892b0aaaf7e154853bccab';	Set after a fetch
-		$this->datec=time();
-		$this->datem=time();
-		$this->webcal_login='dolibspec';
+		$this->datec=$now;
+		$this->datem=$now;
 
-		$this->datelastlogin=time();
-		$this->datepreviouslogin=time();
+		$this->datelastlogin=$now;
+		$this->datepreviouslogin=$now;
 		$this->statut=1;
 
 		//$this->societe_id = 1;	For external users
diff --git a/htdocs/user/fiche.php b/htdocs/user/fiche.php
index 779d0cf54234d355e139834b8251bc526ecb7e57..3e695b63e2ac96c8c52b49a026a9e5d875572798 100644
--- a/htdocs/user/fiche.php
+++ b/htdocs/user/fiche.php
@@ -875,7 +875,7 @@ if (($action == 'create') || ($action == 'adduserldap'))
     print '<tr><td valign="top">'.$langs->trans("Signature").'</td>';
     print '<td>';
     require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-    $doleditor=new DolEditor('signature',GETPOST('signature'),'',280,'dolibarr_mailings','In',true,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,8,72);
+    $doleditor=new DolEditor('signature',GETPOST('signature'),'',138,'dolibarr_mailings','In',true,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,90);
     print $doleditor->Create(1);
     print '</td></tr>';
 
@@ -1778,7 +1778,7 @@ else
             if ($caneditfield)
             {
 	            require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-	            $doleditor=new DolEditor('signature',$object->signature,'',280,'dolibarr_mailings','In',true,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,8,72);
+	            $doleditor=new DolEditor('signature',$object->signature,'',138,'dolibarr_mailings','In',false,true,empty($conf->global->FCKEDITOR_ENABLE_USERSIGN)?0:1,ROWS_4,72);
 	            print $doleditor->Create(1);
             }
             else
diff --git a/htdocs/webservices/demo_wsclient_order.php-NORUN b/htdocs/webservices/demo_wsclient_order.php-NORUN
index 5617c5cdd5dffe288a1c574cfa5a6793908ca239..dedb4cdf1e0f5f3eea47b98940f9859de7b72d9e 100755
--- a/htdocs/webservices/demo_wsclient_order.php-NORUN
+++ b/htdocs/webservices/demo_wsclient_order.php-NORUN
@@ -136,6 +136,6 @@ echo '</pre>';
 echo '<h4>SOAP Message</h4>';
 echo '<pre>' . htmlspecialchars($soapclient2->response, ENT_QUOTES) . '</pre>';
 
-echo '</body>'."\n";;
-echo '</html>'."\n";;
+echo '</body>'."\n";
+echo '</html>'."\n";
 ?>
diff --git a/htdocs/webservices/server_invoice.php b/htdocs/webservices/server_invoice.php
index 014eba8fcb4a1a64c78f097505599b7b73365f52..3e5d630510216ec5822577123e5bbdcf43478093 100755
--- a/htdocs/webservices/server_invoice.php
+++ b/htdocs/webservices/server_invoice.php
@@ -161,7 +161,7 @@ $server->wsdl->addComplexType(
         'total_net' => array('name'=>'type','type'=>'xsd:double'),
         'total_vat' => array('name'=>'type','type'=>'xsd:double'),
         'total' => array('name'=>'type','type'=>'xsd:double'),
-        'note' => array('name'=>'note','type'=>'xsd:string'),
+        'note_private' => array('name'=>'note_private','type'=>'xsd:string'),
         'note_public' => array('name'=>'note_public','type'=>'xsd:string'),
         'status' => array('name'=>'status','type'=>'xsd:int'),
         'close_code' => array('name'=>'close_code','type'=>'xsd:string'),
@@ -324,7 +324,7 @@ function getInvoice($authentication,$id='',$ref='',$ref_ext='')
                         'total_net' => $invoice->total_ht,
                         'total_vat' => $invoice->total_tva,
                         'total' => $invoice->total_ttc,
-                        'note' => $invoice->note?$invoice->note:'',
+                        'note_private' => $invoice->note_private?$invoice->note_private:'',
                         'note_public' => $invoice->note_public?$invoice->note_public:'',
                         'status'=> $invoice->statut,
                         'close_code' => $invoice->close_code?$invoice->close_code:'',
@@ -454,7 +454,7 @@ function getInvoicesForThirdParty($authentication,$idthirdparty)
                     'total_net' => $invoice->total_ht,
                     'total_vat' => $invoice->total_tva,
                     'total' => $invoice->total_ttc,
-                    'note' => $invoice->note?$invoice->note:'',
+                    'note_private' => $invoice->note_private?$invoice->note_private:'',
                     'note_public' => $invoice->note_public?$invoice->note_public:'',
                     'status'=> $invoice->statut,
                     'close_code' => $invoice->close_code?$invoice->close_code:'',
@@ -517,7 +517,7 @@ function createInvoice($authentication,$invoice)
         $newobject->type=$invoice['type'];
         $newobject->ref_ext=$invoice['ref_ext'];
         $newobject->date=dol_stringtotime($invoice['date'],'dayrfc');
-        $newobject->note=$invoice['note'];
+        $newobject->note_private=$invoice['note_private'];
         $newobject->note_public=$invoice['note_public'];
         $newobject->statut=$invoice['status'];
         $newobject->fk_project=$invoice['project_id'];
diff --git a/htdocs/webservices/server_order.php b/htdocs/webservices/server_order.php
index ee311e17bc1fbfc012a91755c71ae431a128eaec..25839b5d76d67b151e7b2b564775b000166895e7 100644
--- a/htdocs/webservices/server_order.php
+++ b/htdocs/webservices/server_order.php
@@ -179,7 +179,7 @@ $server->wsdl->addComplexType(
 				'remise_percent' => array('name'=>'remise_percent','type'=>'xsd:string'),
 				'remise_absolue' => array('name'=>'remise_absolue','type'=>'xsd:string'),
 				'source' => array('name'=>'source','type'=>'xsd:string'),
-				'note' => array('name'=>'note','type'=>'xsd:string'),
+				'note_private' => array('name'=>'note_private','type'=>'xsd:string'),
 				'note_public' => array('name'=>'note_public','type'=>'xsd:string'),
 				'project_id' => array('name'=>'project_id','type'=>'xsd:string'),
 
@@ -399,7 +399,7 @@ function getOrder($authentication,$id='',$ref='',$ref_ext='')
 
 					'source' => $order->source,
 					'facturee' => $order->facturee,
-					'note' => $order->note,
+					'note_private' => $order->note_private,
 					'note_public' => $order->note_public,
 					'cond_reglement_id' => $order->cond_reglement_id,
 					'cond_reglement_code' => $order->cond_reglement_code,
@@ -556,7 +556,7 @@ function getOrdersForThirdParty($authentication,$idthirdparty)
 
 					'source' => $order->source,
 					'facturee' => $order->facturee,
-					'note' => $order->note,
+					'note_private' => $order->note_private,
 					'note_public' => $order->note_public,
 					'cond_reglement_id' => $order->cond_reglement_id,
 					'cond_reglement' => $order->cond_reglement,
@@ -633,7 +633,7 @@ function createOrder($authentication,$order)
 		$newobject->ref_ext=$order['ref_ext'];
 		$newobject->date=dol_stringtotime($order['date'],'dayrfc');
 		$newobject->date_lim_reglement=dol_stringtotime($order['date_due'],'dayrfc');
-		$newobject->note=$order['note'];
+		$newobject->note_private=$order['note_private'];
 		$newobject->note_public=$order['note_public'];
 		$newobject->statut=$order['status'];
 		$newobject->facturee=$order['facturee'];
diff --git a/htdocs/webservices/server_supplier_invoice.php b/htdocs/webservices/server_supplier_invoice.php
index 42e5dda763620c5bdef3b9b00a61d252a69b7dfe..0655b0cd7299b064cefc4b8558bb484a90244664 100755
--- a/htdocs/webservices/server_supplier_invoice.php
+++ b/htdocs/webservices/server_supplier_invoice.php
@@ -144,7 +144,7 @@ $server->wsdl->addComplexType(
         'total_net' => array('name'=>'type','type'=>'xsd:double'),
         'total_vat' => array('name'=>'type','type'=>'xsd:double'),
         'total' => array('name'=>'type','type'=>'xsd:double'),
-        'note' => array('name'=>'note','type'=>'xsd:string'),
+        'note_private' => array('name'=>'note_private','type'=>'xsd:string'),
         'note_public' => array('name'=>'note_public','type'=>'xsd:string'),
         'status' => array('name'=>'status','type'=>'xsd:int'),
         'close_code' => array('name'=>'close_code','type'=>'xsd:string'),
@@ -293,7 +293,7 @@ function getSupplierInvoice($authentication,$id='',$ref='',$ref_ext='')
                         'date_term'=>dol_print_date($invoice->date_echeance,'dayhourrfc'),
                         'label'=>$invoice->libelle,
                         'paid'=>$invoice->paye,
-                        'note'=>$invoice->note,
+                        'note_private'=>$invoice->note_private,
                         'note_public'=>$invoice->note_public,
                         'close_code'=>$invoice->close_code,
                         'close_note'=>$invoice->close_note,
@@ -425,7 +425,7 @@ function getSupplierInvoicesForThirdParty($authentication,$idthirdparty)
                     'date_term'=>dol_print_date($invoice->date_echeance,'dayhourrfc'),
                     'label'=>$invoice->libelle,
                     'paid'=>$invoice->paye,
-                    'note'=>$invoice->note,
+                    'note_private'=>$invoice->note_private,
                     'note_public'=>$invoice->note_public,
                     'close_code'=>$invoice->close_code,
                     'close_note'=>$invoice->close_note,
diff --git a/htdocs/webservices/server_thirdparty.php b/htdocs/webservices/server_thirdparty.php
index 525d6df3bf395cacb2b033018e31c9dae97dac1d..448da44ece244cf75983e6c9cef11c20105e0689 100755
--- a/htdocs/webservices/server_thirdparty.php
+++ b/htdocs/webservices/server_thirdparty.php
@@ -98,7 +98,8 @@ $thirdparty_fields= array(
         'supplier_code_accountancy' => array('name'=>'supplier_code_accountancy','type'=>'xsd:string'),
         'date_creation' => array('name'=>'date_creation','type'=>'xsd:dateTime'),
         'date_modification' => array('name'=>'date_modification','type'=>'xsd:dateTime'),
-        'note' => array('name'=>'note','type'=>'xsd:string'),
+        'note_private' => array('name'=>'note_private','type'=>'xsd:string'),
+		'note_public' => array('name'=>'note_public','type'=>'xsd:string'),
     	'address' => array('name'=>'address','type'=>'xsd:string'),
     	'zip' => array('name'=>'zip','type'=>'xsd:string'),
     	'town' => array('name'=>'town','type'=>'xsd:string'),
@@ -323,7 +324,9 @@ function getThirdParty($authentication,$id='',$ref='',$ref_ext='')
 			            'capital' => $thirdparty->capital,
 			   			'barcode' => $thirdparty->barcode,
 			            'vat_used' => $thirdparty->tva_assuj,
-				        'vat_number' => $thirdparty->tva_intra);
+				        'vat_number' => $thirdparty->tva_intra,
+						'note_private' => $thirdparty->note_private,
+						'note_public' => $thirdparty->note_public);
 				
 				//Retreive all extrafield for thirdsparty
 				// fetch optionals attributes and labels
@@ -410,7 +413,8 @@ function createThirdParty($authentication,$thirdparty)
         $newobject->code_compta=$thirdparty['customer_code_accountancy'];
         $newobject->code_compta_fournisseur=$thirdparty['supplier_code_accountancy'];
         $newobject->date_creation=$now;
-        $newobject->note=$thirdparty['note'];
+        $newobject->note_private=$thirdparty['note_private'];
+        $newobject->note_public=$thirdparty['note_public'];
         $newobject->address=$thirdparty['address'];
         $newobject->zip=$thirdparty['zip'];
         $newobject->town=$thirdparty['town'];
@@ -530,7 +534,8 @@ function updateThirdParty($authentication,$thirdparty)
 			$object->code_compta=$thirdparty['customer_code_accountancy'];
 			$object->code_compta_fournisseur=$thirdparty['supplier_code_accountancy'];
 			$object->date_creation=$now;
-			$object->note=$thirdparty['note'];
+			$object->note_private=$thirdparty['note_private'];
+			$object->note_public=$thirdparty['note_public'];
 			$object->address=$thirdparty['address'];
 			$object->zip=$thirdparty['zip'];
 			$object->town=$thirdparty['town'];
diff --git a/htdocs/webservices/server_user.php b/htdocs/webservices/server_user.php
index 7ff24220b847ee8d577b8a144460a4249664cc66..5b644b150bf5818e1a0092c114fdd395aee85d25 100644
--- a/htdocs/webservices/server_user.php
+++ b/htdocs/webservices/server_user.php
@@ -357,10 +357,6 @@ function getUser($authentication,$id,$ref='',$ref_ext='')
 						'fk_thirdparty' => $user->societe_id,
 						'fk_contact' => $user->contact_id,
 						'fk_member' => $user->fk_member,
-						'webcal_login' => $user->webcal_login,
-						'phenix_login' => $user->phenix_login,
-						'phenix_pass' => $user->phenix_pass,
-						'phenix_pass_crypted' => $user->phenix_pass_crypted,
 						'datelastlogin' => dol_print_date($user->datelastlogin,'dayhourrfc'),
 						'datepreviouslogin' => dol_print_date($user->datepreviouslogin,'dayhourrfc'),
 						'statut' => $user->statut,
diff --git a/scripts/invoices/rebuild_merge_pdf.php b/scripts/invoices/rebuild_merge_pdf.php
index f4984331a515c0041988d785c202246c4a042159..6360735ab6712bc5079c437d0cd9df917b9b0ea5 100755
--- a/scripts/invoices/rebuild_merge_pdf.php
+++ b/scripts/invoices/rebuild_merge_pdf.php
@@ -36,7 +36,6 @@ if (substr($sapi_type, 0, 3) == 'cgi') {
 // Include Dolibarr environment
 require_once($path."../../htdocs/master.inc.php");
 // After this $db is an opened handler to database. We close it at end of file.
-require_once(DOL_DOCUMENT_ROOT."/cron/functions_cron.lib.php");
 require_once(DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php");
 require_once(DOL_DOCUMENT_ROOT."/core/modules/facture/modules_facture.php");
 require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php");
@@ -179,7 +178,7 @@ if (in_array('payments',$filter) && in_array('nopayment',$filter))
 
 // Define SQL and SQL request to select invoices
 // Use $filter, $dateafterdate, datebeforedate, $paymentdateafter, $paymentdatebefore
-$result=rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, 1, $regenerate);
+$result=rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, 1, $regenerate, $option);
 
 
 
diff --git a/test/phpunit/CategorieTest.php b/test/phpunit/CategorieTest.php
index 128a52796dfc2bdb52f1d3456e072ce3efd762b0..501781b309d69967d7b102bb947db449e4289860 100755
--- a/test/phpunit/CategorieTest.php
+++ b/test/phpunit/CategorieTest.php
@@ -276,10 +276,6 @@ class CategorieTest extends PHPUnit_Framework_TestCase
         print __METHOD__." retarray size=".count($retarray)."\n";
         $this->assertTrue(is_array($retarray));
 
-        $retarray=$localobject->is_fille($localobject2);
-        print __METHOD__." retarry size=".count($retarray)."\n";
-        $this->assertFalse($retarray);
-
         return $localobject->id;
     }
 
diff --git a/test/phpunit/ContactTest.php b/test/phpunit/ContactTest.php
index 83dd603ba3e37a706606e852e835f295f9971fb3..bac26a28485db6980e44d18d1a25e8bc3ee34634 100755
--- a/test/phpunit/ContactTest.php
+++ b/test/phpunit/ContactTest.php
@@ -189,8 +189,8 @@ class ContactTest extends PHPUnit_Framework_TestCase
 
 		$localobject->oldcopy=dol_clone($localobject);
 
-		$localobject->note='New note after update';
-		//$localobject->note_public='New note public after update';
+		$localobject->note_private='New private note after update';
+		$localobject->note_public='New public note after update';
 		$localobject->lastname='New name';
 		$localobject->firstname='New firstname';
 		$localobject->address='New address';
@@ -205,15 +205,18 @@ class ContactTest extends PHPUnit_Framework_TestCase
 		$localobject->email='newemail@newemail.com';
 		$localobject->jabberid='New im id';
 		$localobject->default_lang='es_ES';
+		
 		$result=$localobject->update($localobject->id,$user);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
     	$this->assertLessThan($result, 0, 'Contact::update error');
-		$result=$localobject->update_note($localobject->note);
+		
+    	$result=$localobject->update_note_private($localobject->note_private);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	$this->assertLessThan($result, 0, 'Contact::update_note error');
-		//$result=$localobject->update_note_public($localobject->note_public);
-    	//print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	//$this->assertLessThan($result, 0);
+    	$this->assertLessThan($result, 0, 'Contact::update_note_private error');
+		
+    	$result=$localobject->update_note_public($localobject->note_public);
+		print __METHOD__." id=".$localobject->id." result=".$result."\n";
+    	$this->assertLessThan($result, 0, 'Contact::update_note_public error');
 
 		$newobject=new Contact($this->savdb);
     	$result=$newobject->fetch($localobject->id);
diff --git a/test/phpunit/HolidayTest.php b/test/phpunit/HolidayTest.php
index eabfdf4bcfce21561e5a531c8aa6248ea58e692f..f0bb254ce25405ce302cbf6da24f906fafc6d3c5 100644
--- a/test/phpunit/HolidayTest.php
+++ b/test/phpunit/HolidayTest.php
@@ -183,8 +183,8 @@ class HolidayTest extends PHPUnit_Framework_TestCase
 
 		$localobject->oldcopy=dol_clone($localobject);
 
-		$localobject->note='New note after update';
-		//$localobject->note_public='New note public after update';
+		$localobject->note_private='New private note after update';
+		$localobject->note_public='New public note after update';
 		$localobject->lastname='New name';
 		$localobject->firstname='New firstname';
 		$localobject->address='New address';
@@ -199,15 +199,19 @@ class HolidayTest extends PHPUnit_Framework_TestCase
 		$localobject->email='newemail@newemail.com';
 		$localobject->jabberid='New im id';
 		$localobject->default_lang='es_ES';
+		
 		$result=$localobject->update($localobject->id,$user);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
     	$this->assertLessThan($result, 0, 'Holiday::update error');
-		$result=$localobject->update_note($localobject->note);
+		
+    	$result=$localobject->update_note_private($localobject->note_private);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	$this->assertLessThan($result, 0, 'Holiday::update_note error');
-		//$result=$localobject->update_note_public($localobject->note_public);
-    	//print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	//$this->assertLessThan($result, 0);
+    	$this->assertLessThan($result, 0, 'Holiday::update_note_private error');
+		
+    	$result=$localobject->update_note_public($localobject->note_public);
+    	print __METHOD__." id=".$localobject->id." result=".$result."\n";
+    	$this->assertLessThan($result, 0, 'Holiday::update_note_public error');
+		
 
 		$newobject=new Holiday($this->savdb);
     	$result=$newobject->fetch($localobject->id);
diff --git a/test/phpunit/SocieteTest.php b/test/phpunit/SocieteTest.php
index c7b3434218da981eb55ed9a8f56c553089d27d98..619bf98dbe752737e4f64ac6dab41b2f27d666f1 100755
--- a/test/phpunit/SocieteTest.php
+++ b/test/phpunit/SocieteTest.php
@@ -189,8 +189,8 @@ class SocieteTest extends PHPUnit_Framework_TestCase
 		$langs=$this->savlangs;
 		$db=$this->savdb;
 
-		$localobject->note='New note after update';
-		//$localobject->note_public='New note public after update';
+		$localobject->note_private='New private note after update';
+		$localobject->note_public='New public note after update';
 		$localobject->name='New name';
 		$localobject->address='New address';
 		$localobject->zip='New zip';
@@ -205,15 +205,18 @@ class SocieteTest extends PHPUnit_Framework_TestCase
 		$localobject->idprof2='new idprof2';
 		$localobject->idprof3='new idprof3';
 		$localobject->idprof4='new idprof4';
+		
 		$result=$localobject->update($localobject->id,$user);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
     	$this->assertLessThan($result, 0);
-		$result=$localobject->update_note($localobject->note);
+		
+    	$result=$localobject->update_note_private($localobject->note_private);
     	print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	$this->assertLessThan($result, 0);
-		//$result=$localobject->update_note_public($localobject->note_public);
-    	//print __METHOD__." id=".$localobject->id." result=".$result."\n";
-    	//$this->assertLessThan($result, 0);
+    	$this->assertLessThan($result, 0, 'Holiday::update_note_private error');
+		
+    	$result=$localobject->update_note_public($localobject->note_public);
+    	print __METHOD__." id=".$localobject->id." result=".$result."\n";
+    	$this->assertLessThan($result, 0, 'Holiday::update_note_public error');
 
 		$newobject=new Societe($this->savdb);
     	$result=$newobject->fetch($localobject->id);
diff --git a/test/phpunit/WebservicesInvoicesTest.php b/test/phpunit/WebservicesInvoicesTest.php
index 65983390cfdd0edd3011f52f87582a713c386f0c..6f04f5320e23ff964a038546f1826318309c71e1 100755
--- a/test/phpunit/WebservicesInvoicesTest.php
+++ b/test/phpunit/WebservicesInvoicesTest.php
@@ -118,11 +118,11 @@ class WebservicesInvoicesTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSInvoices_xxx
+     * testWSInvoicesXxx
      *
      * @return int
      */
-    public function testWSInvoices_xxx()
+    public function testWSInvoicesXxx()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;
diff --git a/test/phpunit/WebservicesOrdersTest.php b/test/phpunit/WebservicesOrdersTest.php
index a4571557a4867a6a5e32c4ddefcc32a2cae0470f..750c33fa30a1263686b4c44bec8b4784fa715c13 100755
--- a/test/phpunit/WebservicesOrdersTest.php
+++ b/test/phpunit/WebservicesOrdersTest.php
@@ -118,11 +118,11 @@ class WebservicesOrdersTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSOrder_xxx
+     * testWSOrderXxx
      *
      * @return int
      */
-    public function testWSOrder_xxx()
+    public function testWSOrderXxx()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;
@@ -178,11 +178,11 @@ class WebservicesOrdersTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSOther_GetVersions
+     * testWSOtherGetVersions
      *
      * @return int
      */
-    public function testWSOther_GetVersions()
+    public function testWSOtherGetVersions()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;
diff --git a/test/phpunit/WebservicesOtherTest.php b/test/phpunit/WebservicesOtherTest.php
index e06477e7de948d72c92c02c5b6b4000980203180..e8a8a6bd19c6dcc350a831019dd3f97a1b1f7adc 100755
--- a/test/phpunit/WebservicesOtherTest.php
+++ b/test/phpunit/WebservicesOtherTest.php
@@ -118,11 +118,11 @@ class WebservicesOtherTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSOther_GetVersions
+     * testWSOtherGetVersions
      *
      * @return int
      */
-    public function testWSOther_GetVersions()
+    public function testWSOtherGetVersions()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;
diff --git a/test/phpunit/WebservicesThirdpartyTest.php b/test/phpunit/WebservicesThirdpartyTest.php
index b28ac8fa2d82b3b0d168abc167132b5a5dbf5e84..83c7c0ce14df344e5fa67d59ab9199ba5a9ac6a6 100755
--- a/test/phpunit/WebservicesThirdpartyTest.php
+++ b/test/phpunit/WebservicesThirdpartyTest.php
@@ -118,11 +118,11 @@ class WebservicesThirdpartyTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSThirdparty_xxx
+     * testWSThirdpartyXxx
      *
      * @return int
      */
-    public function testWSThirdparty_xxx()
+    public function testWSThirdpartyXxx()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;
diff --git a/test/phpunit/WebservicesUserTest.php b/test/phpunit/WebservicesUserTest.php
index 9ef2278015b94544a1a8191345782ad38618b5de..832fd1ea4cb8353244c7cebf888d1d07bec57b7f 100755
--- a/test/phpunit/WebservicesUserTest.php
+++ b/test/phpunit/WebservicesUserTest.php
@@ -118,11 +118,11 @@ class WebservicesUserTest extends PHPUnit_Framework_TestCase
 
 
     /**
-     * testWSUser_xxx
+     * testWSUserXxx
      *
      * @return int
      */
-    public function testWSUser_xxx()
+    public function testWSUserXxx()
     {
     	global $conf,$user,$langs,$db;
     	$conf=$this->savconf;