diff --git a/modules/attachments/attachments_content.php b/modules/attachments/attachments_content.php
index 45e43f456522b2aacc682e1ac6041da47aaa6232..77797f82935f79fc9aae11c9080cb7795f4d9e4c 100755
--- a/modules/attachments/attachments_content.php
+++ b/modules/attachments/attachments_content.php
@@ -567,6 +567,15 @@ if (isset($_POST['add']) && $_POST['add']) {
                         unset($_SESSION['transmissionContacts']);
                         
                         //copie de la version PDF de la pièce si mode de conversion sur le client
+                        if (
+                            $_SESSION['upfile']['fileNamePdfOnTmp'] != '' &&
+                            empty($_REQUEST['templateOffice'])
+                        ) {
+                            //case onlyConvert
+                            $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
+                            $stmt = $db->query($query);
+                            $_REQUEST['templateOffice'] = $stmt->fetchObject()->template_id;
+                        }
                         if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == true && $_SESSION['upfile']['fileNamePdfOnTmp'] != '' && isset($_REQUEST['templateOffice'])){
 							$_SESSION['new_id'] = $id;
                             $file    = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
diff --git a/modules/attachments/choose_attachment.php b/modules/attachments/choose_attachment.php
index 80bdbc019837751c0d485996d3217811f7461aae..7c6605c1efdbb169a4f9db62530eb96cfb6f2edc 100755
--- a/modules/attachments/choose_attachment.php
+++ b/modules/attachments/choose_attachment.php
@@ -92,7 +92,56 @@ $upFileOK = false;
         <input type="hidden" name="dir" value="indexing_searching" />
         <input type="hidden" name="page" value="choose_attachment" />
         <?php
-            if (!empty($_SESSION['upfile']['local_path']) && empty($_SESSION['error'])) { ?>
+            if (!empty($_SESSION['upfile']['local_path']) && empty($_SESSION['error'])) { 
+                //launch auto convert in PDF
+                if (
+                    strtolower($_SESSION['upfile']['format']) == 'odt' ||
+                    strtolower($_SESSION['upfile']['format']) == 'docx'
+                ) {
+                    require_once 'modules/content_management/class/class_content_manager_tools.php';
+                    $cM = new content_management_tools();
+                    if (
+                        file_exists('custom'.DIRECTORY_SEPARATOR. $_SESSION['custom_override_id']
+                                    . DIRECTORY_SEPARATOR . 'modules'. DIRECTORY_SEPARATOR . 'content_management'
+                                    . DIRECTORY_SEPARATOR . 'applet_controller.php'
+                        )
+                    ) {
+                        $path = 'custom/'. $_SESSION['custom_override_id'] .'/modules/content_management/applet_controller.php';
+                    } else {
+                        $path = 'modules/content_management/applet_controller.php';
+                    }
+                    $path_appli = explode('/', $_SESSION['config']['coreurl']);
+                    if(count($path_appli) <> 5){
+                        $path_appli = array_slice($path_appli, 0, 4);
+                        $path_appli = implode('/', $path_appli);
+                    }else{
+                        $path_appli = implode('/', $path_appli);
+                    }
+                    // require_once 'core/class/class_db_pdo.php';
+                    // $database = new Database();
+                    // $query = "select template_id from templates where template_type = 'OFFICE' and template_target = 'attachments'";
+                    // $stmt = $database->query($query);
+                    // $aTemplateId = $stmt->fetchObject()->template_id;
+                    $cookieKey = $_SESSION['sessionName'] . '=' . $_COOKIE[$_SESSION['sessionName']];
+
+                    $onlyConvert = "true";
+                    $cM->generateJNLP(
+                        $path_appli,
+                        $path_appli . '/' . $path,
+                        'newAttachment',
+                        'res_letterbox',
+                        //$aTemplateId,
+                        $_SESSION['doc_id'],
+                        '',
+                        $cookieKey,
+                        $_SESSION['user']['UserId'],
+                        $_SESSION['clientSideCookies'], 
+                        $_SESSION['modules_loaded']['attachments']['convertPdf'],
+                        $onlyConvert
+                    );
+                }
+
+                ?>
                 <i class="fa fa-check-square fa-2x" title="<?php echo _DOWNLOADED_FILE; ?>"></i>
                 <input type="button" id="fileButton" onclick="$j('#file').click();" class="button"
                        value="<?php if($_REQUEST['with_file'] == 'true'){ echo _WITHOUT_FILE; } else {echo $_FILES['file']['name']; }?>"
diff --git a/modules/content_management/applet_controller.php b/modules/content_management/applet_controller.php
index 84487ff68b37f6cdb930e02ccae064fed1788e3b..70e5835597672ce4c4353d6c1384d05293820bad 100755
--- a/modules/content_management/applet_controller.php
+++ b/modules/content_management/applet_controller.php
@@ -153,6 +153,7 @@ if (!empty($_REQUEST['action'])
             && $objectType <> 'attachmentVersion'
             && $objectType <> 'outgoingMail'
             && $objectType <> 'attachmentUpVersion'
+            && $objectType <> 'newAttachment'
             && $objectType != 'transmission'
         ) {
             //case of res -> master or version
@@ -160,6 +161,9 @@ if (!empty($_REQUEST['action'])
         } elseif ($objectType == 'attachment' || $objectType == 'attachmentUpVersion') {
             //case of res -> update attachment
             include 'modules/content_management/retrieve_attachment_from_cm.php';
+        } elseif ($objectType == 'newAttachment') {
+            //case of res -> new attachment with only conversion
+            include 'modules/content_management/retrieve_new_attachment_from_cm.php';
         } else {
             //case of template, templateStyle, or new attachment generation
             include 'modules/content_management/retrieve_template_from_cm.php';
@@ -252,7 +256,15 @@ if (!empty($_REQUEST['action'])
 				'END_MESSAGE' => '',
 			);
 		}
-        unlink($filePathOnTmp);
+        // $file = fopen('cm_xml_begin.log', a);
+        // fwrite($file, '[' . date('Y-m-d H:i:s') . '] ------BEGIN------- ' . PHP_EOL);
+        // foreach ($result as $key => $value) {
+        //     $resultQuery = "key " . $key . " value " . $value;
+        //     fwrite($file, '[' . date('Y-m-d H:i:s') . '] ' . $resultQuery . PHP_EOL);
+        // }
+        // fwrite($file, '[' . date('Y-m-d H:i:s') . '] ------END------- ' . PHP_EOL);
+        // fclose($file);
+        //unlink($filePathOnTmp);
         createXML('SUCCESS', $result);
     } elseif ($_REQUEST['action'] == 'saveObject') {
         if (
@@ -278,7 +290,7 @@ if (!empty($_REQUEST['action'])
             fclose($inF);
 			
 			//Récupération de la version pdf du document
-			if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == "true" && ($objectType == 'attachmentFromTemplate' || $objectType == 'attachment' || $objectType == 'attachmentUpVersion' || $objectType == 'attachmentVersion' || $objectType == 'outgoingMail' || $objectType == 'resourceEdit' || $objectType == 'transmission') && isset($_REQUEST['pdfContent'])){
+			if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == "true" && ($objectType == 'attachmentFromTemplate' || $objectType == 'attachment' || $objectType == 'attachmentUpVersion' || $objectType == 'attachmentVersion' || $objectType == 'outgoingMail' || $objectType == 'resourceEdit' || $objectType == 'transmission' || $objectType == 'newAttachment') && isset($_REQUEST['pdfContent'])){
 				$pdfEncodedContent = str_replace(
 					' ',
 					'+',
@@ -310,7 +322,7 @@ if (!empty($_REQUEST['action'])
                 }
                 if ($objectType == 'resourceEdit') {
                     include 'modules/content_management/save_editRes_from_cm.php';
-                } elseif ($objectType == 'attachmentFromTemplate') {
+                } elseif ($objectType == 'attachmentFromTemplate' || $objectType == 'newAttachment') {
                     include 'modules/content_management/save_attach_res_from_cm.php';
                 } elseif ($objectType == 'attachment') {
                     include 'modules/content_management/save_attach_from_cm.php';
diff --git a/modules/content_management/applet_launcher.php b/modules/content_management/applet_launcher.php
index d41fe0ac8290d5c0e41aa99893fd3332f1cc9728..22a354683aa884a06cb33ae397fa9c2a74e98849 100755
--- a/modules/content_management/applet_launcher.php
+++ b/modules/content_management/applet_launcher.php
@@ -1,230 +1,232 @@
-<?php
-
-if (
-    file_exists('..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR. '..' 
-                    . DIRECTORY_SEPARATOR . 'core'. DIRECTORY_SEPARATOR . 'init.php'
-    )
-) {
-    include_once '../../../../core/init.php';
-} else {
-    include_once '../../core/init.php';
-}
-
-if (
-    file_exists('custom'.DIRECTORY_SEPARATOR. $_SESSION['custom_override_id']
-                . DIRECTORY_SEPARATOR . 'modules'. DIRECTORY_SEPARATOR . 'content_management'
-                . DIRECTORY_SEPARATOR . 'applet_controller.php'
-    )
-) {
-    $path = 'custom/'. $_SESSION['custom_override_id'] .'/modules/content_management/applet_controller.php';
-} else {
-    $path = 'modules/content_management/applet_controller.php';
-}
-
-//ONLY FOR THE TESTS
-/*
-$_REQUEST['objectType'] = 'resource';
-$_REQUEST['objectTable'] = 'res_letterbox';
-$_REQUEST['objectId'] = 104;
-*/
-
-/*
-echo '<pre>';
-print_r($_REQUEST);
-print_r($_SESSION);
-echo '</pre>';
-exit;
-*/
-
-$_SESSION['cm']['resMaster'] = '';
-$_SESSION['cm']['reservationId'] = '';
-
-require_once 'core/class/class_functions.php';
-require_once 'core/class/class_core_tools.php';
-require_once 'core/class/class_db.php';
-require_once 'core/class/class_request.php';
-require_once 'core/class/class_security.php';
-require_once 'core/class/class_resource.php';
-require_once 'core/class/docservers_controler.php';
-require_once 'modules/content_management/class/class_content_manager_tools.php';
-
-$core_tools = new core_tools();
-$core_tools->test_user();
-$core_tools->load_lang();
-$core_tools->load_js();
-$function = new functions();
-$sec = new security();
-$cM = new content_management_tools();
-$cMFeatures = array();
-$cMFeatures = $cM->getCmParameters();
-
-/* Values for objectType :
- * - resource
- * - attachment
- * - attachmentFromTemplate
- * - template
- * - templateStyle
-*/
-if (isset($_REQUEST['objectType'])) {
-    $objectType = $_REQUEST['objectType'];
-} else {
-    $objectType = '';
-}
-if (isset($_REQUEST['attachType']) && $_REQUEST['attachType'] == "outgoing_mail"){
-	$objectType = 'outgoingMail';
-}
-
-if ($objectType == 'templateStyle') {
-    $_REQUEST['objectId'] = $_SESSION['m_admin']['templates']['current_style'];
-}
-
-if (isset($_REQUEST['objectTable'])) {
-    $objectTable = $_REQUEST['objectTable'];
-} else {
-    $objectTable = '';
-}
-if (isset($_REQUEST['objectId'])) {
-    $objectId = $_REQUEST['objectId'];
-} else {
-    $objectId = '';
-}
-
-if (isset($_REQUEST['uniqueId'])) {
-    $uniqueId = $_REQUEST['uniqueId'];
-} else {
-    $uniqueId = '';
-}
-
-if (isset($_REQUEST['contactId'])) {
-    $_SESSION['cm']['contact_id'] = $_REQUEST['contactId'];
-}
-
-if (isset($_REQUEST['addressId'])) {
-    $_SESSION['cm']['address_id'] = $_REQUEST['addressId'];
-}
-
-if (isset($_REQUEST['chronoAttachment'])) {
-    $_SESSION['cm']['chronoAttachment'] = $_REQUEST['chronoAttachment'];
-}
-if ($_REQUEST['resMaster'] <> '') {
-    $_SESSION['cm']['resMaster'] = $_REQUEST['resMaster'];
-    $reservationObjectId = $_SESSION['cm']['resMaster'];
-} else {
-    $reservationObjectId = $objectId;
-}
-if ($objectType == '' || $objectTable == '' || $objectId == '') {
-    $_SESSION['error'] = _PARAM_MISSING_FOR_MAARCHCM_APPLET . ' ' 
-    . $objectType . ' ' . $objectTable . ' ' . $objectId;
-    //echo $_SESSION['error'];exit;
-    header('location: ' . $_SESSION['config']['businessappurl'] 
-        . 'index.php'
-    );
-    exit();
-}
-
-/*
-echo 'objectType : ' . $objectType . '<br>';
-echo 'objectTable : ' . $objectTable . '<br>';
-echo 'objectId : ' . $objectId . '<br>';
-*/
-
-//no reservation for templateStyle and attachment object. TODO : check for attachmentUpVersion
-
-if (!in_array($objectType, array('templateStyle', 'attachmentVersion'))) {
-    //reservation test
-    $cM->deleteExpiredCM();
-    $reservedBy = array();
-    $reservedBy = $cM->isReservedBy(
-        $objectTable,
-        $reservationObjectId
-    );
-    if (
-        $reservedBy['status'] == 'ok' 
-        && $reservedBy['user_id'] != $_SESSION['user']['UserId']
-    ) {
-        if ($reservedBy['fullname'] <> 'empty') {
-            $_SESSION['error'] = _ALREADY_RESERVED . ' ' . _BY . ' : ' 
-                . $reservedBy['fullname'];
-        } else {
-            $_SESSION['error'] = _RESPONSE_ALREADY_RESERVED;
-        }
-        header('location: ' . $_SESSION['config']['businessappurl'] 
-            . 'index.php'
-        );
-        exit();
-    } else {
-        $_SESSION['cm']['reservationId'] = $cM->reserveObject(
-            $objectTable,
-            $reservationObjectId,
-            $_SESSION['user']['UserId']
-        );
-    }
-}
-
-// $cookieKey = '';
-// $cptCook = 0;
-// foreach ($_COOKIE as $key => $value) {
-//     if ($cptCook == 0) {
-//         $cookieKey = $key . '=' . $value;
-//     }
-//     $cptCook++;
-// }
-
-$cookieKey = $_SESSION['sessionName'] . '=' . $_COOKIE[$_SESSION['sessionName']];
-
-//init error session
-$_SESSION['error'] = '';
-
-?>
-<div id="maarchcmdiv">
-    <h3><?php echo _MAARCH_CM_APPLET;?></h3>
-    <br><center><i class="fa fa-spinner fa-pulse" style="font-size:90px" title="<?php echo _LOADING;?>"></i></center>
-    <br>
-    <br><?php echo _DONT_CLOSE;?>
-
-    <div id="maarchcm_error" class="error"></div>
-    <?php   
-    $path_appli = explode('/', $_SESSION['config']['coreurl']);
-    if(count($path_appli) <> 5){
-        $path_appli = array_slice($path_appli, 0, 4);
-        $path_appli = implode('/', $path_appli);
-    }else{
-        $path_appli = implode('/', $path_appli);
-    }
-    $cM->generateJNLP(
-        $path_appli,
-        $path_appli . '/' . $path,
-        $objectType,
-        $objectTable,
-        $objectId,
-        $uniqueId,
-        $cookieKey,
-        $_SESSION['user']['UserId'],
-        $_SESSION['clientSideCookies'], 
-        $_SESSION['modules_loaded']['attachments']['convertPdf']
-    );
-    exit();
-    ?>
-    <resources>
-      <jar href="<?php 
-            echo $_SESSION['config']['coreurl'];?>modules/content_management/dist/maarchCM.jar"/>
-    </resources>
-    <applet-desc main-class="com.maarch.MaarchCM" name="maarchCM" width="625" height="595">
-      <param name="url" value="<?php 
-            echo $_SESSION['config']['coreurl'].$path;
-        ?>">
-        <param name="objectType" value="<?php functions::xecho($objectType);?>">
-        <param name="objectTable" value="<?php functions::xecho($objectTable);?>">
-        <param name="objectId" value="<?php functions::xecho($objectId);?>">
-        <param name="uniqueId" value="<?php functions::xecho($uniqueId);?>">
-        <param name="cookie" value="<?php echo $cookieKey;?>">
-        <param name="userMaarch" value="<?php 
-            echo $cMFeatures['CONFIG']['userMaarchOnClient'];
-        ?>">
-        <param name="userMaarchPwd" value="<?php 
-            echo $cMFeatures['CONFIG']['userPwdMaarchOnClient'];
-        ?>">
-        <param name="psExecMode" value="<?php functions::xecho($cMFeatures['CONFIG']['psExecMode']);?>">
-        <param name="mayscript" value="mayscript" />
-    </applet-desc>
-</div>
+<?php
+
+if (
+    file_exists('..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR. '..' 
+                    . DIRECTORY_SEPARATOR . 'core'. DIRECTORY_SEPARATOR . 'init.php'
+    )
+) {
+    include_once '../../../../core/init.php';
+} else {
+    include_once '../../core/init.php';
+}
+
+if (
+    file_exists('custom'.DIRECTORY_SEPARATOR. $_SESSION['custom_override_id']
+                . DIRECTORY_SEPARATOR . 'modules'. DIRECTORY_SEPARATOR . 'content_management'
+                . DIRECTORY_SEPARATOR . 'applet_controller.php'
+    )
+) {
+    $path = 'custom/'. $_SESSION['custom_override_id'] .'/modules/content_management/applet_controller.php';
+} else {
+    $path = 'modules/content_management/applet_controller.php';
+}
+
+//ONLY FOR THE TESTS
+/*
+$_REQUEST['objectType'] = 'resource';
+$_REQUEST['objectTable'] = 'res_letterbox';
+$_REQUEST['objectId'] = 104;
+*/
+
+/*
+echo '<pre>';
+print_r($_REQUEST);
+print_r($_SESSION);
+echo '</pre>';
+exit;
+*/
+
+$_SESSION['cm']['resMaster'] = '';
+$_SESSION['cm']['reservationId'] = '';
+
+require_once 'core/class/class_functions.php';
+require_once 'core/class/class_core_tools.php';
+require_once 'core/class/class_db.php';
+require_once 'core/class/class_request.php';
+require_once 'core/class/class_security.php';
+require_once 'core/class/class_resource.php';
+require_once 'core/class/docservers_controler.php';
+require_once 'modules/content_management/class/class_content_manager_tools.php';
+
+$core_tools = new core_tools();
+$core_tools->test_user();
+$core_tools->load_lang();
+$core_tools->load_js();
+$function = new functions();
+$sec = new security();
+$cM = new content_management_tools();
+$cMFeatures = array();
+$cMFeatures = $cM->getCmParameters();
+
+/* Values for objectType :
+ * - resource
+ * - attachment
+ * - attachmentFromTemplate
+ * - template
+ * - templateStyle
+*/
+if (isset($_REQUEST['objectType'])) {
+    $objectType = $_REQUEST['objectType'];
+} else {
+    $objectType = '';
+}
+if (isset($_REQUEST['attachType']) && $_REQUEST['attachType'] == "outgoing_mail"){
+	$objectType = 'outgoingMail';
+}
+
+if ($objectType == 'templateStyle') {
+    $_REQUEST['objectId'] = $_SESSION['m_admin']['templates']['current_style'];
+}
+
+if (isset($_REQUEST['objectTable'])) {
+    $objectTable = $_REQUEST['objectTable'];
+} else {
+    $objectTable = '';
+}
+if (isset($_REQUEST['objectId'])) {
+    $objectId = $_REQUEST['objectId'];
+} else {
+    $objectId = '';
+}
+
+if (isset($_REQUEST['uniqueId'])) {
+    $uniqueId = $_REQUEST['uniqueId'];
+} else {
+    $uniqueId = '';
+}
+
+if (isset($_REQUEST['contactId'])) {
+    $_SESSION['cm']['contact_id'] = $_REQUEST['contactId'];
+}
+
+if (isset($_REQUEST['addressId'])) {
+    $_SESSION['cm']['address_id'] = $_REQUEST['addressId'];
+}
+
+if (isset($_REQUEST['chronoAttachment'])) {
+    $_SESSION['cm']['chronoAttachment'] = $_REQUEST['chronoAttachment'];
+}
+if ($_REQUEST['resMaster'] <> '') {
+    $_SESSION['cm']['resMaster'] = $_REQUEST['resMaster'];
+    $reservationObjectId = $_SESSION['cm']['resMaster'];
+} else {
+    $reservationObjectId = $objectId;
+}
+if ($objectType == '' || $objectTable == '' || $objectId == '') {
+    $_SESSION['error'] = _PARAM_MISSING_FOR_MAARCHCM_APPLET . ' ' 
+    . $objectType . ' ' . $objectTable . ' ' . $objectId;
+    //echo $_SESSION['error'];exit;
+    header('location: ' . $_SESSION['config']['businessappurl'] 
+        . 'index.php'
+    );
+    exit();
+}
+
+/*
+echo 'objectType : ' . $objectType . '<br>';
+echo 'objectTable : ' . $objectTable . '<br>';
+echo 'objectId : ' . $objectId . '<br>';
+*/
+
+//no reservation for templateStyle and attachment object. TODO : check for attachmentUpVersion
+
+if (!in_array($objectType, array('templateStyle', 'attachmentVersion'))) {
+    //reservation test
+    $cM->deleteExpiredCM();
+    $reservedBy = array();
+    $reservedBy = $cM->isReservedBy(
+        $objectTable,
+        $reservationObjectId
+    );
+    if (
+        $reservedBy['status'] == 'ok' 
+        && $reservedBy['user_id'] != $_SESSION['user']['UserId']
+    ) {
+        if ($reservedBy['fullname'] <> 'empty') {
+            $_SESSION['error'] = _ALREADY_RESERVED . ' ' . _BY . ' : ' 
+                . $reservedBy['fullname'];
+        } else {
+            $_SESSION['error'] = _RESPONSE_ALREADY_RESERVED;
+        }
+        header('location: ' . $_SESSION['config']['businessappurl'] 
+            . 'index.php'
+        );
+        exit();
+    } else {
+        $_SESSION['cm']['reservationId'] = $cM->reserveObject(
+            $objectTable,
+            $reservationObjectId,
+            $_SESSION['user']['UserId']
+        );
+    }
+}
+
+// $cookieKey = '';
+// $cptCook = 0;
+// foreach ($_COOKIE as $key => $value) {
+//     if ($cptCook == 0) {
+//         $cookieKey = $key . '=' . $value;
+//     }
+//     $cptCook++;
+// }
+
+$cookieKey = $_SESSION['sessionName'] . '=' . $_COOKIE[$_SESSION['sessionName']];
+
+//init error session
+$_SESSION['error'] = '';
+
+?>
+<div id="maarchcmdiv">
+    <h3><?php echo _MAARCH_CM_APPLET;?></h3>
+    <br><center><i class="fa fa-spinner fa-pulse" style="font-size:90px" title="<?php echo _LOADING;?>"></i></center>
+    <br>
+    <br><?php echo _DONT_CLOSE;?>
+
+    <div id="maarchcm_error" class="error"></div>
+    <?php   
+    $path_appli = explode('/', $_SESSION['config']['coreurl']);
+    if(count($path_appli) <> 5){
+        $path_appli = array_slice($path_appli, 0, 4);
+        $path_appli = implode('/', $path_appli);
+    }else{
+        $path_appli = implode('/', $path_appli);
+    }
+    $onlyConvert = "false";
+    $cM->generateJNLP(
+        $path_appli,
+        $path_appli . '/' . $path,
+        $objectType,
+        $objectTable,
+        $objectId,
+        $uniqueId,
+        $cookieKey,
+        $_SESSION['user']['UserId'],
+        $_SESSION['clientSideCookies'], 
+        $_SESSION['modules_loaded']['attachments']['convertPdf'],
+        $onlyConvert
+    );
+    exit();
+    ?>
+    <resources>
+      <jar href="<?php 
+            echo $_SESSION['config']['coreurl'];?>modules/content_management/dist/maarchCM.jar"/>
+    </resources>
+    <applet-desc main-class="com.maarch.MaarchCM" name="maarchCM" width="625" height="595">
+      <param name="url" value="<?php 
+            echo $_SESSION['config']['coreurl'].$path;
+        ?>">
+        <param name="objectType" value="<?php functions::xecho($objectType);?>">
+        <param name="objectTable" value="<?php functions::xecho($objectTable);?>">
+        <param name="objectId" value="<?php functions::xecho($objectId);?>">
+        <param name="uniqueId" value="<?php functions::xecho($uniqueId);?>">
+        <param name="cookie" value="<?php echo $cookieKey;?>">
+        <param name="userMaarch" value="<?php 
+            echo $cMFeatures['CONFIG']['userMaarchOnClient'];
+        ?>">
+        <param name="userMaarchPwd" value="<?php 
+            echo $cMFeatures['CONFIG']['userPwdMaarchOnClient'];
+        ?>">
+        <param name="psExecMode" value="<?php functions::xecho($cMFeatures['CONFIG']['psExecMode']);?>">
+        <param name="mayscript" value="mayscript" />
+    </applet-desc>
+</div>
diff --git a/modules/content_management/class/class_content_manager_tools_Abstract.php b/modules/content_management/class/class_content_manager_tools_Abstract.php
index 442d2e3cfa85022920d7951824ac8abc80779f3f..2fc8664fd13e34c26967db73380c50c5f1454f59 100755
--- a/modules/content_management/class/class_content_manager_tools_Abstract.php
+++ b/modules/content_management/class/class_content_manager_tools_Abstract.php
@@ -1,596 +1,606 @@
-<?php
-
-/*
-*   Copyright 2008-2017 Maarch
-*
-*   This file is part of Maarch Framework.
-*
-*   Maarch Framework 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.
-*
-*   Maarch Framework 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 Maarch Framework. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-/**
-* @brief Contains the functions to manage content_management directory and expiration
-*
-* @file
-* @author Laurent Giovannoni
-* @date $date$
-* @version $Revision$
-* @ingroup content_management
-*/
-
-require_once 'core/class/class_functions.php';
-require_once 'core/class/class_db_pdo.php';
-require_once 'core/class/docservers_controler.php';
-require_once 'core/class/class_security.php';
-require_once 'core/core_tables.php';
-
-abstract class content_management_tools_Abstract
-{
-    //Parameters
-    protected $extensions_xml_path = 'xml/extensions.xml';
-    protected $programs_xml_path = 'xml/programs.xml';
-    protected $parameter_id  = 'content_management_reservation';
-    protected $templateMasterPath = 'modules/templates/templates_src/';
-    //Variables
-    protected $db;
-
-    public function __construct()
-    {
-        if (!isset($_SESSION) OR count($_SESSION) == 0)
-            return null;
-
-        $this->db = new Database();
-        //TODO: PUT IT AN CONFIG FILE WITH 30
-        $_SESSION['config']['content_management_reserved_time'] = 30;
-        if (!is_dir('modules/content_management/tmp/')) {
-            mkdir('modules/content_management/tmp/');
-        }
-    }
-    
-    public function getCmParameters()
-    {
-        if (file_exists(
-            $_SESSION['config']['corepath'] . 'custom/'
-            . $_SESSION['custom_override_id'] 
-            . '/modules/content_management/xml/content_management_features.xml'
-        )
-        ) {
-            $path = $_SESSION['config']['corepath'] . 'custom/'
-                . $_SESSION['custom_override_id'] 
-                . '/modules/content_management/xml/content_management_features.xml';
-        } else {
-            $path = $_SESSION['config']['corepath'] 
-                . 'modules/content_management/xml/content_management_features.xml';
-        }
-        $cMFeatures = array();
-        if (file_exists($path)) {
-            $func = new functions();
-            $cMFeatures = $func->object2array(
-                simplexml_load_file($path)
-            );
-        } else {
-            $cMFeatures['CONFIG']['psExecMode'] = 'KO';
-            $cMFeatures['CONFIG']['userMaarchOnClient'] = '';
-            $cMFeatures['CONFIG']['userPwdMaarchOnClient'] = '';
-        }
-        return $cMFeatures;
-    }
-
-    /**
-    * Returns who reserved the resource
-    *
-    * @param  string $objectTable res table, attachment table, model table, ...
-    * @param  bigint $objectId id of the object res_id, model_id, ...
-    * @return array the user who reserved the resource, else false
-    */
-    public function isReservedBy($objectTable, $objectId)
-    {
-        $timeLimit = $this->computeTimeLimit();
-        $charTofind = $this->parameter_id . '#%#' . $objectTable . '#' . $objectId;
-
-        $query = "select id from " . PARAM_TABLE . " where id like (?) and param_value_int > ?";
-
-        $stmt = $this->db->query($query, array($charTofind, $timeLimit));
-        
-        if ($res = $stmt->fetchObject()) {
-
-            $arrayUser = array();
-            $arrayUser = explode("#", $res->id);
-            if ($arrayUser[1] <> '') {
-                $query = "select user_id, lastname, firstname "
-                    . "from " . USERS_TABLE . " where user_id = ? and enabled = 'Y'";
-                
-                $stmt = $this->db->query($query, array($arrayUser[1]));
-                
-                $arrayReturn = array();
-                if ($resUser = $stmt->fetchObject()) {
-                    $arrayReturn['fullname'] = $resUser->firstname . ' '
-                        . $resUser->lastname;
-                    $arrayReturn['user_id'] = $resUser->user_id;
-                } else {
-                    $arrayReturn['fullname'] = 'empty';
-                }
-                $arrayReturn['status'] = 'ok';
-                return $arrayReturn;
-            } else {
-                $arrayReturn['status'] = 'ko';
-            }
-        } else {
-            $arrayReturn['status'] = 'ko';
-        }
-        return $arrayReturn;
-    }
-
-    /**
-    * Close the content_management reservation
-    *
-    * @param string $CMId content_management id
-    * @return nothing
-    */
-    public function closeReservation($CMId)
-    {
-        $query = "delete from " . PARAM_TABLE
-            . " where id = ?";
-        $stmt = $this->db->query($query, array($CMId));
-    }
-
-    /**
-    * Update the expiration date of the content_management reservation for the connected user
-    *
-    * @param  string $CMId the content_management id
-    * @param  string $userId the content_management id
-    * @return nothing
-    */
-    public function updateExpiryDate($CMId, $userId)
-    {
-        $timeLimit = $this->computeTimeLimit() + (
-            $_SESSION['config']['content_management_reserved_time'] * 60
-        );
-        $charTofind = $this->parameter_id . '#' . $userId . '%';
-        $query = "update " . PARAM_TABLE
-               . " set param_value_int = ? "
-               . " where id like ?"
-               . " and param_value_string = ?";
-        $stmt = $this->db->query(
-            $query, 
-            array($timeLimit, $charTofind, $CMId)
-        );
-    }
-
-    /**
-    * Reserved the object for content_management
-    * Add an expiration date of the content_management reservation for the connected user
-    *
-    * @param  string $objectTable the res table
-    * @param  string $objectId the res_id
-    * @param  string $CMId the content_management id
-    * @param  string $userId the content_management id
-    * @return string the reservation id
-    */
-    public function reserveObject($objectTable, $objectId, $userId)
-    {
-        $timeLimit = $this->computeTimeLimit() + (
-            $_SESSION['config']['content_management_reserved_time'] * 60
-        );
-        //If exists Delete
-        $charTofind = $this->parameter_id . '#' . $userId . '#' . $objectTable
-                    . '#' . $objectId;
-        $query = "delete from " . PARAM_TABLE
-               . " where id = ?";
-        $stmt = $this->db->query($query, array($charTofind));
-        $query = "insert into " . PARAM_TABLE
-               . " (id, param_value_int)"
-               . " values(?, ?)";
-        $stmt = $this->db->query($query, array($charTofind, $timeLimit));
-        return $charTofind;
-    }
-
-    /**
-    * Delete the resource in the tmp content_management dir if necessary
-    *
-    * @return nothing
-    */
-    public function deleteExpiredCM()
-    {
-        $timeLimit = $this->computeTimeLimit();
-        $query = "delete from " . PARAM_TABLE
-            . " where param_value_int < ? "
-            . " and id like ? ";
-        $stmt = $this->db->query($query, array($timeLimit, $this->parameter_id . '%'));
-    }
-    
-    /**
-    * Delete the resource for the disconnected user
-    *
-    * @return nothing
-    */
-    public function deleteUserCM()
-    {
-        $query = "delete from " . PARAM_TABLE
-            . " where id like ?";
-        $stmt = $this->db->query($query, array('content_management_reservation#' 
-            . $_SESSION['user']['UserId'] . '%')
-        );
-    }
-
-    /**
-    * Delete the content_management tmp if necessary
-    *
-    * @param string $dir path to the tmp dir
-    * @return nothing
-    */
-    protected function deleteDirectory($dir)
-    {
-        if (!file_exists($dir)) return true;
-        if (!is_dir($dir) || is_link($dir)) return unlink($dir);
-            foreach (scandir($dir) as $item) {
-                if ($item == '.' || $item == '..') continue;
-                if (!$this->deleteDirectory($dir . "/" . $item)) {
-                    chmod($dir . "/" . $item, 0777);
-                    if (!$this->deleteDirectory($dir . "/" . $item)) return false;
-                };
-            }
-            return rmdir($dir);
-    }
-
-    /**
-    * Returns time before expiration of the content_management reservation
-    *
-    * @param  string $CMId the content_management id
-    * @return bigint the time in secon before expiration
-    */
-    public function timeBeforeExpiration($CMId)
-    {
-        $now = $this->computeTimeLimit();
-        $charTofind = $this->parameter_id . '%';
-        $query = "select param_value_int as time"
-               . " from " . PARAM_TABLE
-               . " where id like ?"
-               . " and param_value_string = ?";
-        $stmt = $this->db->query($query, array($charTofind, $CMId));
-        if ($res = $stmt->fetchObject()) {
-            $secBeforeExpiration = $res->time - $now;
-            if ($secBeforeExpiration < 0)  {
-                return 0;
-            } else {
-                return $secBeforeExpiration;
-            }
-        } else {
-            return 0;
-        }
-    }
-
-    /**
-    * Returns the program to update the resource with content_management
-    *
-    * @param  string $mimeType mime type of the resource
-    * @return array the program and status ok if mime type allowed for content_management
-    */
-    public function isMimeTypeAllowedForCM($mimeType, $ext) {
-        $typeState = 'ko';
-        $programPath = '';
-        if ($mimeType <> '' && $ext <> '') {
-            $path = $_SESSION['config']['corepath'] . 'custom/'
-                  . $_SESSION['custom_override_id'] . '/apps/'
-                  . $_SESSION['config']['app_id'] . '/xml/extensions.xml';
-            if (!file_exists($path)) {
-                $path =  $_SESSION['config']['corepath'] . '/apps/'
-                      . $_SESSION['config']['app_id'] . '/xml/extensions.xml';
-            }
-            $xmlconfig = simplexml_load_file($path);
-            $extList = array();
-            $i = 0;
-            foreach ($xmlconfig->FORMAT as $FORMAT) {
-                $extList[$i] = array(
-                    'name' => (string) $FORMAT->name,
-                    'mime' => (string) $FORMAT->mime,
-                    'web_dav_update' => (string) $FORMAT->web_dav_update,
-                    'default_program' => (string) $FORMAT->default_program,
-                );
-                $i++;
-            }
-            for ($i=0;$i<count($extList);$i++) {
-                if (
-                    $extList[$i]['mime'] == $mimeType
-                    && strtolower($extList[$i]['name']) == strtolower($ext)
-                    && strtolower($extList[$i]['web_dav_update']) == 'true'
-                ) {
-                    $typeState = 'ok';
-                    $programPath = $extList[$i]['default_program'];
-                    break;
-                }
-            }
-        }
-        $arrayReturn = array(
-            'status' => $typeState,
-            'programPath' => $programPath,
-        );
-        return $arrayReturn;
-    }
-
-    /**
-    * Compute the time limit for a content_management session
-    *
-    * @return string the time limit in timestamp
-    */
-    public function computeTimeLimit()
-    {
-        $timeLimit = mktime(
-            date('H'),
-            date('i'),
-            date('s'),
-            date('m'),
-            date('d'),
-            date('Y')
-        );
-        return $timeLimit;
-    }
-
-    /**
-    * Generate JLNP file to launch the JNLP
-    *
-    * 
-    */
-    public function generateJNLP(
-        $jar_url,
-        $maarchcm_url,
-        $objectType,
-        $objectTable,
-        $objectId,
-        $uniqueId,
-        $cookieKey,
-        $user,
-        $clientSideCookies,
-        $convertPdf = "false"
-    ) {
-        $docXML = new DomDocument('1.0', "UTF-8");
-
-        //create unique id for APPLET
-        $uid_applet_name = $_SESSION['user']['UserId'].'_maarchCM_'.rand();
-
-        $jnlp_name = $uid_applet_name.'.jnlp';
-
-        if ($_SESSION['config']['debug']) {
-            $inF = fopen(
-                $_SESSION['config']['tmppath'] . 'log_jnlp_' . $_SESSION['user']['UserId'] . '.log',
-                'a'
-            );
-            fwrite(
-                $inF, 
-                '------------------' . PHP_EOL
-                . 'CREATE JNLP------------------'
-                . $_SERVER['SERVER_NAME'] . ' ' . $_SESSION['user']['UserId'] . ' ' . date('D, j M Y H:i:s O') .PHP_EOL
-            );
-            fwrite($inF, '|||||||||||||||||SERVER DETAILS BEGIN FOR CREATE JNLP|||||||||||||||||' . PHP_EOL);
-            foreach($_SERVER as $key => $value) {
-                fwrite($inF, $key . " : " . $value . PHP_EOL);
-            }
-            fwrite($inF, '|||||||||||||||||SERVER DETAILS END FOR CREATE JNLP|||||||||||||||||' . PHP_EOL);
-            fwrite($inF, "jar_url : " . $jar_url . PHP_EOL);
-            fwrite($inF, "jnlp_name : " . $jnlp_name . PHP_EOL);
-            fwrite($inF, "maarchcm_url : " . $maarchcm_url . PHP_EOL);
-            fwrite($inF, "objectType : " . $objectType . PHP_EOL);
-            fwrite($inF, "objectTable : " . $objectTable . PHP_EOL);
-            fwrite($inF, "objectId : " . $objectId . PHP_EOL);
-            fwrite($inF, "uniqueId : " . $uniqueId . PHP_EOL);
-            fwrite($inF, "cookieKey : " . $cookieKey . PHP_EOL);
-            fwrite($inF, "idApplet : " . $idApplet . PHP_EOL);
-            fwrite($inF, "clientSideCookies : " . $clientSideCookies . PHP_EOL);
-            fwrite($inF, "user : " . $user . PHP_EOL);
-            fwrite($inF, "convertPdf : " . $convertPdf . PHP_EOL);
-            $listArguments = '?url=' . urlencode($maarchcm_url)
-                . '&objectType=' . $objectType
-                . '&objectTable=' . $objectTable
-                . '&objectId=' . $objectId
-                . '&uniqueId=' . $uniqueId
-                . '&cookie=' . $cookieKey
-                . '&clientSideCookies=' . $clientSideCookies
-                . '&idApplet=' . $uid_applet_name
-                . '&userMaarch=' . $user
-                . '&convertPdf=' . $convertPdf;
-            fwrite($inF, "listArguments : " . $listArguments . PHP_EOL);
-            fclose($inF);
-        }
-        
-        $jnlp_balise=$docXML->createElement("jnlp");
-        $jnlp_attribute1 = $docXML->createAttribute('spec'); 
-        $jnlp_attribute1->value = '6.0+';
-        $jnlp_balise->appendChild($jnlp_attribute1); 
-        $jnlp_attribute2 = $docXML->createAttribute('codebase'); 
-        $jnlp_attribute2->value = $jar_url.'/apps/maarch_entreprise/tmp/';
-        $jnlp_balise->appendChild($jnlp_attribute2);
-        $jnlp_attribute3 = $docXML->createAttribute('href'); 
-        
-        $jnlp_attribute3->value = $jnlp_name;
-
-        $jnlp_balise->appendChild($jnlp_attribute3); 
-
-        $info_balise=$docXML->createElement("information");
-
-        $title_balise=$docXML->createElement("title","Editeur de modèle de document");
-
-        $vendor_balise=$docXML->createElement("vendor","MAARCH");
-
-        $homepage_balise=$docXML->createElement("homepage");
-        $homepage_attribute = $docXML->createAttribute('href');
-        $homepage_attribute->value = 'http://maarch.com';
-        $homepage_balise->appendChild($homepage_attribute);
-
-        $desc_balise=$docXML->createElement("description","Génère votre document avec méta-données associées au courrier grâce à des champs de fusion.");
-        
-        $descshort_balise=$docXML->createElement("description","Génère votre document avec méta-données.");
-        $descshort_attribute = $docXML->createAttribute('kind');
-        $descshort_attribute->value = 'short';
-        $descshort_balise->appendChild($descshort_attribute);
-
-        $offline_balise=$docXML->createElement("offline-allowed");
-
-        $security_balise=$docXML->createElement("security");
-
-        $permission_balise=$docXML->createElement("all-permissions");
-
-        $resources_balise=$docXML->createElement("resources");
-
-        $j2se_balise=$docXML->createElement("j2se");
-        $j2se_attribute = $docXML->createAttribute('version');
-        $j2se_attribute->value = '1.6+';
-        $j2se_balise->appendChild($j2se_attribute);
-
-        $jar_balise=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/maarchCM.jar';
-        $jar_balise->appendChild($jar_attribute);
-        $jar_attribute = $docXML->createAttribute('main');
-        $jar_attribute->value = 'true';
-        $jar_balise->appendChild($jar_attribute);
-
-        //begin ext libs
-        $jar_balise_1=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-4.5.2.jar';
-        $jar_balise_1->appendChild($jar_attribute);
-
-        $jar_balise_2=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-cache-4.5.2.jar';
-        $jar_balise_2->appendChild($jar_attribute);
-
-        $jar_balise_3=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-win-4.5.2.jar';
-        $jar_balise_3->appendChild($jar_attribute);
-
-        $jar_balise_4=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpcore-4.4.4.jar';
-        $jar_balise_4->appendChild($jar_attribute);
-
-        $jar_balise_5=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/plugin.jar';
-        $jar_balise_5->appendChild($jar_attribute);
-
-        $jar_balise_6=$docXML->createElement("jar");
-        $jar_attribute = $docXML->createAttribute('href');
-        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/commons-logging-1.2.jar';
-        $jar_balise_6->appendChild($jar_attribute);
-        //end ext libs
-
-        //$applet_balise=$docXML->createElement("applet-desc");
-        $applet_balise=$docXML->createElement("application-desc");
-        $applet_attribute1 = $docXML->createAttribute('main-class');
-        $applet_attribute1->value = 'com.maarch.MaarchCM';
-        $applet_balise->appendChild($applet_attribute1);
-
-        //arguments
-        $param1_balise = $docXML->createElement("argument", $maarchcm_url);
-
-        if (empty($objectType)) {
-            $objectType = 'empty';
-        }
-        $param2_balise=$docXML->createElement("argument", htmlentities($objectType));
-
-        if (empty($objectTable)) {
-            $objectTable = 'empty';
-        }
-        $param3_balise=$docXML->createElement("argument", htmlentities($objectTable));
-
-        if (empty($objectId)) {
-            $objectId = 'empty';
-        }
-        $param4_balise=$docXML->createElement("argument", htmlentities($objectId));
-
-        if (empty($uniqueId)) {
-            $uniqueId = 'empty';
-        }
-        $param5_balise=$docXML->createElement("argument", htmlentities($uniqueId));
-
-        if (empty($cookieKey)) {
-            $cookieKey = 'empty';
-        }
-        $param6_balise=$docXML->createElement("argument", htmlentities($cookieKey));
-
-        if (empty($clientSideCookies)) {
-            $clientSideCookies = 'empty';
-        }
-        $param7_balise=$docXML->createElement("argument", htmlentities($clientSideCookies));
-
-        if (empty($uid_applet_name)) {
-            $uid_applet_name = 'empty';
-        }
-        $param8_balise=$docXML->createElement("argument", htmlentities($uid_applet_name));
-
-        if (empty($user)) {
-            $user = 'empty';
-        }
-        $param9_balise=$docXML->createElement("argument", htmlentities($user));
-
-        if (empty($convertPdf)) {
-            $convertPdf = 'false';
-        }
-        $param10_balise=$docXML->createElement("argument", htmlentities($convertPdf));
-
-        $jnlp_balise->appendChild($info_balise); 
-        $info_balise->appendChild($title_balise); 
-        $info_balise->appendChild($vendor_balise); 
-        $info_balise->appendChild($homepage_balise); 
-        $info_balise->appendChild($desc_balise); 
-        $info_balise->appendChild($descshort_balise); 
-        $info_balise->appendChild($offline_balise); 
-
-        $jnlp_balise->appendChild($security_balise); 
-        $security_balise->appendChild($permission_balise); 
-
-        $jnlp_balise->appendChild($resources_balise); 
-        $resources_balise->appendChild($j2se_balise); 
-        $resources_balise->appendChild($jar_balise); 
-        $resources_balise->appendChild($jar_balise_1);
-        $resources_balise->appendChild($jar_balise_2);
-        $resources_balise->appendChild($jar_balise_3);
-        $resources_balise->appendChild($jar_balise_4);
-        $resources_balise->appendChild($jar_balise_5);
-        $resources_balise->appendChild($jar_balise_6);
-
-        $jnlp_balise->appendChild($applet_balise);
-        $applet_balise->appendChild($param1_balise);
-        $applet_balise->appendChild($param2_balise);
-        $applet_balise->appendChild($param3_balise);
-        $applet_balise->appendChild($param4_balise);
-        $applet_balise->appendChild($param5_balise);
-        $applet_balise->appendChild($param6_balise);
-        $applet_balise->appendChild($param7_balise);
-        $applet_balise->appendChild($param8_balise);
-        $applet_balise->appendChild($param9_balise);
-        $applet_balise->appendChild($param10_balise);
-
-        $docXML->appendChild($jnlp_balise);  
-
-        $filename = $_SESSION['config']['tmppath'].$jnlp_name;
-
-        $docXML->save($filename); 
-
-        $fp = fopen($_SESSION['config']['tmppath'].$uid_applet_name.".lck", 'w+');
-
-        $_SESSION['cm_applet'][$_SESSION['user']['UserId']][$uid_applet_name]=$uid_applet_name.'.lck';
-
-        $file = $jar_url."/apps/maarch_entreprise/tmp/".$jnlp_name;
-
-        //echo '<a id="jnlp_file" href="'.$file.'" onclick="window.location.href=\''.$file.'\';self.close();"></a>';
-        echo '<script>window.location.href=\''.$file.'\';if($(\'CMApplet\')) {destroyModal(\'CMApplet\');};if($(\'CMApplet\')) {destroyModal(\'CMApplet\');};</script>';
-        exit();
-        /*echo '<a id="jnlp_file" href="'.$_SESSION['config']['businessappurl'].'index.php?page=get_jnlp_file&module=content_management&display=true&filename='.$_SESSION['user']['UserId'].'_maarchCM"></a>';
-        echo '<script>setTimeout(function() {this.window.close();}, 5000);document.getElementById("jnlp_file").click();</script>';
-        exit();*/
-    }
-}
+<?php
+
+/*
+*   Copyright 2008-2017 Maarch
+*
+*   This file is part of Maarch Framework.
+*
+*   Maarch Framework 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.
+*
+*   Maarch Framework 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 Maarch Framework. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+* @brief Contains the functions to manage content_management directory and expiration
+*
+* @file
+* @author Laurent Giovannoni
+* @date $date$
+* @version $Revision$
+* @ingroup content_management
+*/
+
+require_once 'core/class/class_functions.php';
+require_once 'core/class/class_db_pdo.php';
+require_once 'core/class/docservers_controler.php';
+require_once 'core/class/class_security.php';
+require_once 'core/core_tables.php';
+
+abstract class content_management_tools_Abstract
+{
+    //Parameters
+    protected $extensions_xml_path = 'xml/extensions.xml';
+    protected $programs_xml_path = 'xml/programs.xml';
+    protected $parameter_id  = 'content_management_reservation';
+    protected $templateMasterPath = 'modules/templates/templates_src/';
+    //Variables
+    protected $db;
+
+    public function __construct()
+    {
+        if (!isset($_SESSION) OR count($_SESSION) == 0)
+            return null;
+
+        $this->db = new Database();
+        //TODO: PUT IT AN CONFIG FILE WITH 30
+        $_SESSION['config']['content_management_reserved_time'] = 30;
+        if (!is_dir('modules/content_management/tmp/')) {
+            mkdir('modules/content_management/tmp/');
+        }
+    }
+    
+    public function getCmParameters()
+    {
+        if (file_exists(
+            $_SESSION['config']['corepath'] . 'custom/'
+            . $_SESSION['custom_override_id'] 
+            . '/modules/content_management/xml/content_management_features.xml'
+        )
+        ) {
+            $path = $_SESSION['config']['corepath'] . 'custom/'
+                . $_SESSION['custom_override_id'] 
+                . '/modules/content_management/xml/content_management_features.xml';
+        } else {
+            $path = $_SESSION['config']['corepath'] 
+                . 'modules/content_management/xml/content_management_features.xml';
+        }
+        $cMFeatures = array();
+        if (file_exists($path)) {
+            $func = new functions();
+            $cMFeatures = $func->object2array(
+                simplexml_load_file($path)
+            );
+        } else {
+            $cMFeatures['CONFIG']['psExecMode'] = 'KO';
+            $cMFeatures['CONFIG']['userMaarchOnClient'] = '';
+            $cMFeatures['CONFIG']['userPwdMaarchOnClient'] = '';
+        }
+        return $cMFeatures;
+    }
+
+    /**
+    * Returns who reserved the resource
+    *
+    * @param  string $objectTable res table, attachment table, model table, ...
+    * @param  bigint $objectId id of the object res_id, model_id, ...
+    * @return array the user who reserved the resource, else false
+    */
+    public function isReservedBy($objectTable, $objectId)
+    {
+        $timeLimit = $this->computeTimeLimit();
+        $charTofind = $this->parameter_id . '#%#' . $objectTable . '#' . $objectId;
+
+        $query = "select id from " . PARAM_TABLE . " where id like (?) and param_value_int > ?";
+
+        $stmt = $this->db->query($query, array($charTofind, $timeLimit));
+        
+        if ($res = $stmt->fetchObject()) {
+
+            $arrayUser = array();
+            $arrayUser = explode("#", $res->id);
+            if ($arrayUser[1] <> '') {
+                $query = "select user_id, lastname, firstname "
+                    . "from " . USERS_TABLE . " where user_id = ? and enabled = 'Y'";
+                
+                $stmt = $this->db->query($query, array($arrayUser[1]));
+                
+                $arrayReturn = array();
+                if ($resUser = $stmt->fetchObject()) {
+                    $arrayReturn['fullname'] = $resUser->firstname . ' '
+                        . $resUser->lastname;
+                    $arrayReturn['user_id'] = $resUser->user_id;
+                } else {
+                    $arrayReturn['fullname'] = 'empty';
+                }
+                $arrayReturn['status'] = 'ok';
+                return $arrayReturn;
+            } else {
+                $arrayReturn['status'] = 'ko';
+            }
+        } else {
+            $arrayReturn['status'] = 'ko';
+        }
+        return $arrayReturn;
+    }
+
+    /**
+    * Close the content_management reservation
+    *
+    * @param string $CMId content_management id
+    * @return nothing
+    */
+    public function closeReservation($CMId)
+    {
+        $query = "delete from " . PARAM_TABLE
+            . " where id = ?";
+        $stmt = $this->db->query($query, array($CMId));
+    }
+
+    /**
+    * Update the expiration date of the content_management reservation for the connected user
+    *
+    * @param  string $CMId the content_management id
+    * @param  string $userId the content_management id
+    * @return nothing
+    */
+    public function updateExpiryDate($CMId, $userId)
+    {
+        $timeLimit = $this->computeTimeLimit() + (
+            $_SESSION['config']['content_management_reserved_time'] * 60
+        );
+        $charTofind = $this->parameter_id . '#' . $userId . '%';
+        $query = "update " . PARAM_TABLE
+               . " set param_value_int = ? "
+               . " where id like ?"
+               . " and param_value_string = ?";
+        $stmt = $this->db->query(
+            $query, 
+            array($timeLimit, $charTofind, $CMId)
+        );
+    }
+
+    /**
+    * Reserved the object for content_management
+    * Add an expiration date of the content_management reservation for the connected user
+    *
+    * @param  string $objectTable the res table
+    * @param  string $objectId the res_id
+    * @param  string $CMId the content_management id
+    * @param  string $userId the content_management id
+    * @return string the reservation id
+    */
+    public function reserveObject($objectTable, $objectId, $userId)
+    {
+        $timeLimit = $this->computeTimeLimit() + (
+            $_SESSION['config']['content_management_reserved_time'] * 60
+        );
+        //If exists Delete
+        $charTofind = $this->parameter_id . '#' . $userId . '#' . $objectTable
+                    . '#' . $objectId;
+        $query = "delete from " . PARAM_TABLE
+               . " where id = ?";
+        $stmt = $this->db->query($query, array($charTofind));
+        $query = "insert into " . PARAM_TABLE
+               . " (id, param_value_int)"
+               . " values(?, ?)";
+        $stmt = $this->db->query($query, array($charTofind, $timeLimit));
+        return $charTofind;
+    }
+
+    /**
+    * Delete the resource in the tmp content_management dir if necessary
+    *
+    * @return nothing
+    */
+    public function deleteExpiredCM()
+    {
+        $timeLimit = $this->computeTimeLimit();
+        $query = "delete from " . PARAM_TABLE
+            . " where param_value_int < ? "
+            . " and id like ? ";
+        $stmt = $this->db->query($query, array($timeLimit, $this->parameter_id . '%'));
+    }
+    
+    /**
+    * Delete the resource for the disconnected user
+    *
+    * @return nothing
+    */
+    public function deleteUserCM()
+    {
+        $query = "delete from " . PARAM_TABLE
+            . " where id like ?";
+        $stmt = $this->db->query($query, array('content_management_reservation#' 
+            . $_SESSION['user']['UserId'] . '%')
+        );
+    }
+
+    /**
+    * Delete the content_management tmp if necessary
+    *
+    * @param string $dir path to the tmp dir
+    * @return nothing
+    */
+    protected function deleteDirectory($dir)
+    {
+        if (!file_exists($dir)) return true;
+        if (!is_dir($dir) || is_link($dir)) return unlink($dir);
+            foreach (scandir($dir) as $item) {
+                if ($item == '.' || $item == '..') continue;
+                if (!$this->deleteDirectory($dir . "/" . $item)) {
+                    chmod($dir . "/" . $item, 0777);
+                    if (!$this->deleteDirectory($dir . "/" . $item)) return false;
+                };
+            }
+            return rmdir($dir);
+    }
+
+    /**
+    * Returns time before expiration of the content_management reservation
+    *
+    * @param  string $CMId the content_management id
+    * @return bigint the time in secon before expiration
+    */
+    public function timeBeforeExpiration($CMId)
+    {
+        $now = $this->computeTimeLimit();
+        $charTofind = $this->parameter_id . '%';
+        $query = "select param_value_int as time"
+               . " from " . PARAM_TABLE
+               . " where id like ?"
+               . " and param_value_string = ?";
+        $stmt = $this->db->query($query, array($charTofind, $CMId));
+        if ($res = $stmt->fetchObject()) {
+            $secBeforeExpiration = $res->time - $now;
+            if ($secBeforeExpiration < 0)  {
+                return 0;
+            } else {
+                return $secBeforeExpiration;
+            }
+        } else {
+            return 0;
+        }
+    }
+
+    /**
+    * Returns the program to update the resource with content_management
+    *
+    * @param  string $mimeType mime type of the resource
+    * @return array the program and status ok if mime type allowed for content_management
+    */
+    public function isMimeTypeAllowedForCM($mimeType, $ext) {
+        $typeState = 'ko';
+        $programPath = '';
+        if ($mimeType <> '' && $ext <> '') {
+            $path = $_SESSION['config']['corepath'] . 'custom/'
+                  . $_SESSION['custom_override_id'] . '/apps/'
+                  . $_SESSION['config']['app_id'] . '/xml/extensions.xml';
+            if (!file_exists($path)) {
+                $path =  $_SESSION['config']['corepath'] . '/apps/'
+                      . $_SESSION['config']['app_id'] . '/xml/extensions.xml';
+            }
+            $xmlconfig = simplexml_load_file($path);
+            $extList = array();
+            $i = 0;
+            foreach ($xmlconfig->FORMAT as $FORMAT) {
+                $extList[$i] = array(
+                    'name' => (string) $FORMAT->name,
+                    'mime' => (string) $FORMAT->mime,
+                    'web_dav_update' => (string) $FORMAT->web_dav_update,
+                    'default_program' => (string) $FORMAT->default_program,
+                );
+                $i++;
+            }
+            for ($i=0;$i<count($extList);$i++) {
+                if (
+                    $extList[$i]['mime'] == $mimeType
+                    && strtolower($extList[$i]['name']) == strtolower($ext)
+                    && strtolower($extList[$i]['web_dav_update']) == 'true'
+                ) {
+                    $typeState = 'ok';
+                    $programPath = $extList[$i]['default_program'];
+                    break;
+                }
+            }
+        }
+        $arrayReturn = array(
+            'status' => $typeState,
+            'programPath' => $programPath,
+        );
+        return $arrayReturn;
+    }
+
+    /**
+    * Compute the time limit for a content_management session
+    *
+    * @return string the time limit in timestamp
+    */
+    public function computeTimeLimit()
+    {
+        $timeLimit = mktime(
+            date('H'),
+            date('i'),
+            date('s'),
+            date('m'),
+            date('d'),
+            date('Y')
+        );
+        return $timeLimit;
+    }
+
+    /**
+    * Generate JLNP file to launch the JNLP
+    *
+    * 
+    */
+    public function generateJNLP(
+        $jar_url,
+        $maarchcm_url,
+        $objectType,
+        $objectTable,
+        $objectId,
+        $uniqueId,
+        $cookieKey,
+        $user,
+        $clientSideCookies,
+        $convertPdf = "false",
+        $onlyConvert = "false"
+    ) {
+        $docXML = new DomDocument('1.0', "UTF-8");
+
+        //create unique id for APPLET
+        $uid_applet_name = $_SESSION['user']['UserId'].'_maarchCM_'.rand();
+
+        $jnlp_name = $uid_applet_name.'.jnlp';
+
+        if ($_SESSION['config']['debug']) {
+            $inF = fopen(
+                $_SESSION['config']['tmppath'] . 'log_jnlp_' . $_SESSION['user']['UserId'] . '.log',
+                'a'
+            );
+            fwrite(
+                $inF, 
+                '------------------' . PHP_EOL
+                . 'CREATE JNLP------------------'
+                . $_SERVER['SERVER_NAME'] . ' ' . $_SESSION['user']['UserId'] . ' ' . date('D, j M Y H:i:s O') .PHP_EOL
+            );
+            fwrite($inF, '|||||||||||||||||SERVER DETAILS BEGIN FOR CREATE JNLP|||||||||||||||||' . PHP_EOL);
+            foreach($_SERVER as $key => $value) {
+                fwrite($inF, $key . " : " . $value . PHP_EOL);
+            }
+            fwrite($inF, '|||||||||||||||||SERVER DETAILS END FOR CREATE JNLP|||||||||||||||||' . PHP_EOL);
+            fwrite($inF, "jar_url : " . $jar_url . PHP_EOL);
+            fwrite($inF, "jnlp_name : " . $jnlp_name . PHP_EOL);
+            fwrite($inF, "maarchcm_url : " . $maarchcm_url . PHP_EOL);
+            fwrite($inF, "objectType : " . $objectType . PHP_EOL);
+            fwrite($inF, "objectTable : " . $objectTable . PHP_EOL);
+            fwrite($inF, "objectId : " . $objectId . PHP_EOL);
+            fwrite($inF, "uniqueId : " . $uniqueId . PHP_EOL);
+            fwrite($inF, "cookieKey : " . $cookieKey . PHP_EOL);
+            fwrite($inF, "idApplet : " . $idApplet . PHP_EOL);
+            fwrite($inF, "clientSideCookies : " . $clientSideCookies . PHP_EOL);
+            fwrite($inF, "user : " . $user . PHP_EOL);
+            fwrite($inF, "convertPdf : " . $convertPdf . PHP_EOL);
+            fwrite($inF, "onlyConvert : " . $onlyConvert . PHP_EOL);
+            $listArguments = '?url=' . urlencode($maarchcm_url)
+                . '&objectType=' . $objectType
+                . '&objectTable=' . $objectTable
+                . '&objectId=' . $objectId
+                . '&uniqueId=' . $uniqueId
+                . '&cookie=' . $cookieKey
+                . '&clientSideCookies=' . $clientSideCookies
+                . '&idApplet=' . $uid_applet_name
+                . '&userMaarch=' . $user
+                . '&convertPdf=' . $convertPdf
+                . '&onlyConvert=' . $onlyConvert;
+            fwrite($inF, "listArguments : " . $listArguments . PHP_EOL);
+            fclose($inF);
+        }
+        
+        $jnlp_balise=$docXML->createElement("jnlp");
+        $jnlp_attribute1 = $docXML->createAttribute('spec'); 
+        $jnlp_attribute1->value = '6.0+';
+        $jnlp_balise->appendChild($jnlp_attribute1); 
+        $jnlp_attribute2 = $docXML->createAttribute('codebase'); 
+        $jnlp_attribute2->value = $jar_url.'/apps/maarch_entreprise/tmp/';
+        $jnlp_balise->appendChild($jnlp_attribute2);
+        $jnlp_attribute3 = $docXML->createAttribute('href'); 
+        
+        $jnlp_attribute3->value = $jnlp_name;
+
+        $jnlp_balise->appendChild($jnlp_attribute3); 
+
+        $info_balise=$docXML->createElement("information");
+
+        $title_balise=$docXML->createElement("title","Editeur de modèle de document");
+
+        $vendor_balise=$docXML->createElement("vendor","MAARCH");
+
+        $homepage_balise=$docXML->createElement("homepage");
+        $homepage_attribute = $docXML->createAttribute('href');
+        $homepage_attribute->value = 'http://maarch.com';
+        $homepage_balise->appendChild($homepage_attribute);
+
+        $desc_balise=$docXML->createElement("description","Génère votre document avec méta-données associées au courrier grâce à des champs de fusion.");
+        
+        $descshort_balise=$docXML->createElement("description","Génère votre document avec méta-données.");
+        $descshort_attribute = $docXML->createAttribute('kind');
+        $descshort_attribute->value = 'short';
+        $descshort_balise->appendChild($descshort_attribute);
+
+        $offline_balise=$docXML->createElement("offline-allowed");
+
+        $security_balise=$docXML->createElement("security");
+
+        $permission_balise=$docXML->createElement("all-permissions");
+
+        $resources_balise=$docXML->createElement("resources");
+
+        $j2se_balise=$docXML->createElement("j2se");
+        $j2se_attribute = $docXML->createAttribute('version');
+        $j2se_attribute->value = '1.6+';
+        $j2se_balise->appendChild($j2se_attribute);
+
+        $jar_balise=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/maarchCM.jar';
+        $jar_balise->appendChild($jar_attribute);
+        $jar_attribute = $docXML->createAttribute('main');
+        $jar_attribute->value = 'true';
+        $jar_balise->appendChild($jar_attribute);
+
+        //begin ext libs
+        $jar_balise_1=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-4.5.2.jar';
+        $jar_balise_1->appendChild($jar_attribute);
+
+        $jar_balise_2=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-cache-4.5.2.jar';
+        $jar_balise_2->appendChild($jar_attribute);
+
+        $jar_balise_3=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpclient-win-4.5.2.jar';
+        $jar_balise_3->appendChild($jar_attribute);
+
+        $jar_balise_4=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/httpcore-4.4.4.jar';
+        $jar_balise_4->appendChild($jar_attribute);
+
+        $jar_balise_5=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/plugin.jar';
+        $jar_balise_5->appendChild($jar_attribute);
+
+        $jar_balise_6=$docXML->createElement("jar");
+        $jar_attribute = $docXML->createAttribute('href');
+        $jar_attribute->value = $jar_url.'/modules/content_management/dist/lib/commons-logging-1.2.jar';
+        $jar_balise_6->appendChild($jar_attribute);
+        //end ext libs
+
+        //$applet_balise=$docXML->createElement("applet-desc");
+        $applet_balise=$docXML->createElement("application-desc");
+        $applet_attribute1 = $docXML->createAttribute('main-class');
+        $applet_attribute1->value = 'com.maarch.MaarchCM';
+        $applet_balise->appendChild($applet_attribute1);
+
+        //arguments
+        $param1_balise = $docXML->createElement("argument", $maarchcm_url);
+
+        if (empty($objectType)) {
+            $objectType = 'empty';
+        }
+        $param2_balise=$docXML->createElement("argument", htmlentities($objectType));
+
+        if (empty($objectTable)) {
+            $objectTable = 'empty';
+        }
+        $param3_balise=$docXML->createElement("argument", htmlentities($objectTable));
+
+        if (empty($objectId)) {
+            $objectId = 'empty';
+        }
+        $param4_balise=$docXML->createElement("argument", htmlentities($objectId));
+
+        if (empty($uniqueId)) {
+            $uniqueId = 'empty';
+        }
+        $param5_balise=$docXML->createElement("argument", htmlentities($uniqueId));
+
+        if (empty($cookieKey)) {
+            $cookieKey = 'empty';
+        }
+        $param6_balise=$docXML->createElement("argument", htmlentities($cookieKey));
+
+        if (empty($clientSideCookies)) {
+            $clientSideCookies = 'empty';
+        }
+        $param7_balise=$docXML->createElement("argument", htmlentities($clientSideCookies));
+
+        if (empty($uid_applet_name)) {
+            $uid_applet_name = 'empty';
+        }
+        $param8_balise=$docXML->createElement("argument", htmlentities($uid_applet_name));
+
+        if (empty($user)) {
+            $user = 'empty';
+        }
+        $param9_balise=$docXML->createElement("argument", htmlentities($user));
+
+        if (empty($convertPdf)) {
+            $convertPdf = 'false';
+        }
+        $param10_balise=$docXML->createElement("argument", htmlentities($convertPdf));
+
+        if (empty($onlyConvert)) {
+            $onlyConvert = 'false';
+        }
+        $param11_balise=$docXML->createElement("argument", htmlentities($onlyConvert));
+        
+
+        $jnlp_balise->appendChild($info_balise); 
+        $info_balise->appendChild($title_balise); 
+        $info_balise->appendChild($vendor_balise); 
+        $info_balise->appendChild($homepage_balise); 
+        $info_balise->appendChild($desc_balise); 
+        $info_balise->appendChild($descshort_balise); 
+        $info_balise->appendChild($offline_balise); 
+
+        $jnlp_balise->appendChild($security_balise); 
+        $security_balise->appendChild($permission_balise); 
+
+        $jnlp_balise->appendChild($resources_balise); 
+        $resources_balise->appendChild($j2se_balise); 
+        $resources_balise->appendChild($jar_balise); 
+        $resources_balise->appendChild($jar_balise_1);
+        $resources_balise->appendChild($jar_balise_2);
+        $resources_balise->appendChild($jar_balise_3);
+        $resources_balise->appendChild($jar_balise_4);
+        $resources_balise->appendChild($jar_balise_5);
+        $resources_balise->appendChild($jar_balise_6);
+
+        $jnlp_balise->appendChild($applet_balise);
+        $applet_balise->appendChild($param1_balise);
+        $applet_balise->appendChild($param2_balise);
+        $applet_balise->appendChild($param3_balise);
+        $applet_balise->appendChild($param4_balise);
+        $applet_balise->appendChild($param5_balise);
+        $applet_balise->appendChild($param6_balise);
+        $applet_balise->appendChild($param7_balise);
+        $applet_balise->appendChild($param8_balise);
+        $applet_balise->appendChild($param9_balise);
+        $applet_balise->appendChild($param10_balise);
+        $applet_balise->appendChild($param11_balise);
+
+        $docXML->appendChild($jnlp_balise);  
+
+        $filename = $_SESSION['config']['tmppath'].$jnlp_name;
+
+        $docXML->save($filename); 
+
+        $fp = fopen($_SESSION['config']['tmppath'].$uid_applet_name.".lck", 'w+');
+
+        $_SESSION['cm_applet'][$_SESSION['user']['UserId']][$uid_applet_name]=$uid_applet_name.'.lck';
+
+        $file = $jar_url."/apps/maarch_entreprise/tmp/".$jnlp_name;
+
+        //echo '<a id="jnlp_file" href="'.$file.'" onclick="window.location.href=\''.$file.'\';self.close();"></a>';
+        echo '<script>window.location.href=\''.$file.'\';if($(\'CMApplet\')) {destroyModal(\'CMApplet\');};if($(\'CMApplet\')) {destroyModal(\'CMApplet\');};</script>';
+        exit();
+        /*echo '<a id="jnlp_file" href="'.$_SESSION['config']['businessappurl'].'index.php?page=get_jnlp_file&module=content_management&display=true&filename='.$_SESSION['user']['UserId'].'_maarchCM"></a>';
+        echo '<script>setTimeout(function() {this.window.close();}, 5000);document.getElementById("jnlp_file").click();</script>';
+        exit();*/
+    }
+}
diff --git a/modules/content_management/dist/not_signed/maarchCM.jar b/modules/content_management/dist/not_signed/maarchCM.jar
index 8f864e0297724367de89501e6e16561eb33cbb41..d8283be41269d69429d28dbe35b47ccb8a069e56 100644
Binary files a/modules/content_management/dist/not_signed/maarchCM.jar and b/modules/content_management/dist/not_signed/maarchCM.jar differ
diff --git a/modules/content_management/dist/src/FileManager.java b/modules/content_management/dist/src/FileManager.java
old mode 100755
new mode 100644
index aa2d592950e75b96023cc0acb55fa66cc95b7b1e..cc2ccf8d59671fea428bc00dce86d6699fa57d54
--- a/modules/content_management/dist/src/FileManager.java
+++ b/modules/content_management/dist/src/FileManager.java
@@ -368,4 +368,4 @@ public class FileManager {
         }
     }
     
-}
\ No newline at end of file
+}
diff --git a/modules/content_management/dist/src/MaarchCM.java b/modules/content_management/dist/src/MaarchCM.java
old mode 100755
new mode 100644
index 24ef49333a1e68717f9d562396b63f3c9f2919e2..2ccb0bb013baee640a7ab9fd8e71668be31823df
--- a/modules/content_management/dist/src/MaarchCM.java
+++ b/modules/content_management/dist/src/MaarchCM.java
@@ -68,6 +68,8 @@ public class MaarchCM {
     protected String clientSideCookies;
     protected String uniqueId;
     protected String convertPdf;
+    protected String onlyConvert;
+
     protected String domain;
     protected String userLocalDirTmp;
     protected String userMaarch;
@@ -96,7 +98,9 @@ public class MaarchCM {
     public MyLogger logger;
     public FileManager fM;
     public String fileToEdit;
-    public String editMode;
+    public String editMode;    
+    public String programName;
+
 
     
     public List<String> fileToDelete = new ArrayList<String>();
@@ -131,6 +135,7 @@ public class MaarchCM {
         idApplet = args[7];
         userMaarch = args[8];
         convertPdf = args[9];
+        onlyConvert = args[10];
         
         System.out.println("URL : " + url);
         System.out.println("OBJECT TYPE : " + objectType);
@@ -141,7 +146,8 @@ public class MaarchCM {
         System.out.println("COOKIE : " + cookie);
         System.out.println("CLIENTSIDECOOKIES : " + clientSideCookies);
         System.out.println("USERMAARCH : " + userMaarch);
-        System.out.println("CONVERPDF : " + convertPdf);
+        System.out.println("CONVERTPDF : " + convertPdf);
+        System.out.println("ONLYCONVERT : " + onlyConvert);
         System.out.println("----------CONTROL PARAMETERS----------");
         
         if (
@@ -324,8 +330,21 @@ public class MaarchCM {
     }
 
     public void createPDF(String docxFile, String directory, boolean isUnix) {
+        logger.log("createPDF ", Level.INFO);
         try {
-            System.out.println("mode ! : "+editMode);
+            System.out.println("mode ! : " + editMode);
+            //patch onlyConvert
+            if (onlyConvert.equals("true")) {
+                if ("linux".equals(os) || "mac".equals(os)) {
+                    editMode = "libreoffice";
+                } else {
+                    if("soffice.exe".equals(programName)){
+                        editMode = "libreoffice";
+                    }else{
+                        editMode = "office"; 
+                    }
+                }
+            }
             boolean conversion = true;
             String cmd = "";
             if (docxFile.contains(".odt") || docxFile.contains(".ods") || docxFile.contains(".ODT") || docxFile.contains(".ODS")) {
@@ -339,6 +358,7 @@ public class MaarchCM {
                 }
 
             } else if (docxFile.contains(".doc") || docxFile.contains(".docx") || docxFile.contains(".DOC") || docxFile.contains(".DOCX")) {
+                logger.log("This is MSOffice document ", Level.INFO);
                 if (useExeConvert.equals("false")) {
                     if (isUnix) {
                         cmd = "libreoffice -env:UserInstallation=file://"+userLocalDirTmp+idApplet+"_conv\\ --headless --convert-to pdf --outdir \"" + userLocalDirTmp.substring(0, userLocalDirTmp.length() - 1) + "\" \"" + docxFile + "\"";
@@ -486,7 +506,7 @@ public class MaarchCM {
      */
     public String editObject() throws Exception, InterruptedException, JSException {
 
-        System.out.println("----------BEGIN EDIT OBJECT---------- LGI by Maarch and DIS 22/01/2017");
+        System.out.println("----------BEGIN EDIT OBJECT---------- LGI by Maarch 02/10/2017");
         System.out.println("----------BEGIN LOCAL DIR TMP IF NOT EXISTS----------");
         os = System.getProperty("os.name").toLowerCase();
         boolean isUnix = os.contains("nix") || os.contains("nux");
@@ -552,11 +572,17 @@ public class MaarchCM {
         logger.log("COOKIE : " + cookie, Level.INFO);
         logger.log("CLIENTSIDECOOKIES : " + clientSideCookies, Level.INFO);
         logger.log("USERMAARCH : " + userMaarch, Level.INFO);
+        logger.log("ONLYCONVERT : " + onlyConvert, Level.INFO);
 
         logger.log("----------BEGIN OPEN REQUEST----------", Level.INFO);
-        String urlToSend = url + "?action=editObject&objectType=" + objectType
-                + "&objectTable=" + objectTable + "&objectId=" + objectId
-                + "&uniqueId=" + uniqueId;
+        String urlToSend;
+        
+        urlToSend = url + "?action=editObject&objectType=" + objectType
+            + "&objectTable=" + objectTable + "&objectId=" + objectId
+            + "&uniqueId=" + uniqueId;
+        
+        
+        logger.log("FIRST URL CALL : " + urlToSend, Level.INFO);
         sendHttpRequest(urlToSend, "none", false);
         logger.log("MESSAGE STATUS : " + messageStatus, Level.INFO);
         logger.log("MESSAGE RESULT : ", Level.INFO);
@@ -598,35 +624,41 @@ public class MaarchCM {
             fM.createFile(fileContent, userLocalDirTmp + fileToEdit);
             fileToDelete.add(userLocalDirTmp + fileToEdit);
             
-            Thread theThread;
-            theThread = new Thread(new ProcessLoop(this));
-
-            theThread.start();
-            
-            String actualContent;
             fileContentTosend = "";
-            do {
-                theThread.sleep(3000);
-                File fileTotest = new File(userLocalDirTmp + fileToEdit);
-                if (fileTotest.canRead()) {
-                    actualContent = FileManager.encodeFile(userLocalDirTmp + fileToEdit);
-                    if (!fileContentTosend.equals(actualContent)) {
-                        fileContentTosend = actualContent;
-                        logger.log("----------[SECURITY BACKUP] BEGIN SEND OF THE OBJECT----------", Level.INFO);
-                        String urlToSave = url + "?action=saveObject&objectType=" + objectType
-                                + "&objectTable=" + objectTable + "&objectId=" + objectId
-                                + "&uniqueId=" + uniqueId + "&step=backup&userMaarch=" + userMaarch;
-                        logger.log("[SECURITY BACKUP] URL TO SAVE : " + urlToSave, Level.INFO);
-                        sendHttpRequest(urlToSave, fileContentTosend, false);
-                        logger.log("[SECURITY BACKUP] MESSAGE STATUS : " + messageStatus, Level.INFO);
+            
+            if (onlyConvert.equals("false")) {
+                Thread theThread;
+                theThread = new Thread(new ProcessLoop(this));
+
+                theThread.start();
+
+                String actualContent;
+                
+                do {
+                    theThread.sleep(3000);
+                    File fileTotest = new File(userLocalDirTmp + fileToEdit);
+                    if (fileTotest.canRead()) {
+                        actualContent = FileManager.encodeFile(userLocalDirTmp + fileToEdit);
+                        if (!fileContentTosend.equals(actualContent)) {
+                            fileContentTosend = actualContent;
+                            logger.log("----------[SECURITY BACKUP] BEGIN SEND OF THE OBJECT----------", Level.INFO);
+                            String urlToSave = url + "?action=saveObject&objectType=" + objectType
+                                    + "&objectTable=" + objectTable + "&objectId=" + objectId
+                                    + "&uniqueId=" + uniqueId + "&step=backup&userMaarch=" + userMaarch;
+                            logger.log("[SECURITY BACKUP] URL TO SAVE : " + urlToSave, Level.INFO);
+                            sendHttpRequest(urlToSave, fileContentTosend, false);
+                            logger.log("[SECURITY BACKUP] MESSAGE STATUS : " + messageStatus, Level.INFO);
+                        }
+                    } else {
+                        logger.log(userLocalDirTmp + fileToEdit + " FILE NOT READABLE !!!!!!", Level.INFO);
                     }
-                } else {
-                    logger.log(userLocalDirTmp + fileToEdit + " FILE NOT READABLE !!!!!!", Level.INFO);
                 }
+                while (theThread.isAlive());
+            
+                theThread.interrupt();
             }
-            while (theThread.isAlive());
 
-            theThread.interrupt();
+            
 
             logger.log("----------END EXECUTION OF THE EDITOR----------", Level.INFO);
 
@@ -635,10 +667,13 @@ public class MaarchCM {
             fileContentTosend = FileManager.encodeFile(userLocalDirTmp + fileToEdit);
 
             logger.log("----------END RETRIEVE CONTENT OF THE OBJECT----------", Level.INFO);
+            
+            logger.log("conversion pdf ? " + convertPdf , Level.INFO);
 
             if ("true".equals(convertPdf)) {
                 if ((fileExtension.equalsIgnoreCase("docx") || fileExtension.equalsIgnoreCase("doc") || fileExtension.equalsIgnoreCase("docm") || fileExtension.equalsIgnoreCase("odt") || fileExtension.equalsIgnoreCase("ott"))) {
                     logger.log("----------CONVERSION PDF----------", Level.INFO);
+                    
                     createPDF(userLocalDirTmp + fileToEdit, userLocalDirTmp, isUnix);
 
                     String pdfFile = userLocalDirTmp + "thefile_" + idApplet + ".pdf";
@@ -664,7 +699,8 @@ public class MaarchCM {
 
             String urlToSave = url + "?action=saveObject&objectType=" + objectType
                     + "&objectTable=" + objectTable + "&objectId=" + objectId
-                    + "&uniqueId=" + uniqueId + "&idApplet=" + idApplet + "&step=end&userMaarch=" + userMaarch;
+                    + "&uniqueId=" + uniqueId + "&idApplet=" + idApplet + "&step=end&userMaarch=" + userMaarch
+                    + "&onlyConvert=" + onlyConvert;
             logger.log("----------BEGIN SEND OF THE OBJECT----------", Level.INFO);
             logger.log("URL TO SAVE : " + urlToSave, Level.INFO);
             sendHttpRequest(urlToSave, fileContentTosend, true);
@@ -742,7 +778,6 @@ public class MaarchCM {
         } else {
             logger.log("FILE TO EDIT : " + userLocalDirTmp + fileToEdit, Level.INFO);
 
-            String programName;
             programName = fM.findGoodProgramWithExt(fileExtension);
             String pathProgram;
             pathProgram = fM.findPathProgramInRegistry(programName);
diff --git a/modules/content_management/retrieve_new_attachment_from_cm.php b/modules/content_management/retrieve_new_attachment_from_cm.php
new file mode 100755
index 0000000000000000000000000000000000000000..2aec72af083c2d48feff0e10541a509f5ebb5cc7
--- /dev/null
+++ b/modules/content_management/retrieve_new_attachment_from_cm.php
@@ -0,0 +1,19 @@
+<?php
+//case of res -> new attachment
+
+
+if (!file_exists($_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'])) {
+    $result = array('ERROR' => _THE_DOC . ' ' . $_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'] . ' ' . _EXISTS_OR_RIGHT);
+    createXML('ERROR', $result);
+} else {
+    $func = new functions();
+    $fileExtension = $func->extractFileExt($_SESSION['config']['tmppath'] . $_SESSION['upfile']['name']);
+    $filePathOnTmp = $_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'];
+    // $file = fopen('file.log', a);
+    // fwrite($file, '[' . date('Y-m-d H:i:s') . '] ------BEGIN------- ' . PHP_EOL);
+    // fwrite($file, '[' . date('Y-m-d H:i:s') . '] EXT ' . $fileExtension . PHP_EOL);
+    // fwrite($file, '[' . date('Y-m-d H:i:s') . '] PATH ' . $filePathOnTmp . PHP_EOL);
+    // fclose($file);
+    // $result = array('ERROR' => _THE_DOC . ' ' . $_SESSION['config']['tmppath'] . $_SESSION['upfile']['name'] . ' ' . _EXISTS_OR_RIGHT);
+    // createXML('ERROR', $result);
+}
diff --git a/modules/content_management/save_attach_res_from_cm.php b/modules/content_management/save_attach_res_from_cm.php
index fb9b345d72db0e11d597e1f46dc3d9d5016e5a97..32e99678fc9d63465e1fe7a885092f82d30df610 100755
--- a/modules/content_management/save_attach_res_from_cm.php
+++ b/modules/content_management/save_attach_res_from_cm.php
@@ -2,6 +2,14 @@
 
 //FOR ADD NEW ATTACHMENTS
 
+// case onlyConvert
+if (
+    $_SESSION['modules_loaded']['attachments']['convertPdf'] == true &&
+    $objectType == 'newAttachment'
+){
+    $_SESSION['upfile']['fileNamePdfOnTmp'] = $tmpFilePdfName;
+}
+
 require_once 'modules/attachments/attachments_tables.php';
 
 //new attachment from a template
diff --git a/modules/content_management/xml/IVS/validation_rules.xml b/modules/content_management/xml/IVS/validation_rules.xml
index e60043acc506dac5e1b3dfa817c75df32c56c96e..d5045e7cbf296de00abed4db7b242397fe2205e6 100755
--- a/modules/content_management/xml/IVS/validation_rules.xml
+++ b/modules/content_management/xml/IVS/validation_rules.xml
@@ -7,7 +7,8 @@
 		<parameter name="transmissionNumber" type="identifier" />
 		<parameter name="fileContent" type="string" />
 		<parameter name="fileExtension" type="filename_extension" />
-		<parameter name="pdfContent" type="string" />
+        <parameter name="pdfContent" type="string" />
+		<parameter name="onlyConvert" type="string" />
     </validationRule>
     <validationRule name="cm_applet_launcher" extends="standardForm" mode="error">
     	<parameter name="action" type="identifier" />
diff --git a/modules/templates/class/templates_controler_Abstract.php b/modules/templates/class/templates_controler_Abstract.php
index 1d36490020979a54330e02c409c7cecb00846b44..a1641194a0199720c895b5d6aceb65f83d716c4e 100755
--- a/modules/templates/class/templates_controler_Abstract.php
+++ b/modules/templates/class/templates_controler_Abstract.php
@@ -268,15 +268,20 @@ abstract class templates_controler_Abstract extends ObjectControler implements O
     {
         $this->set_foolish_ids(array('template_id'));
         $this->set_specific_id('template_id');
-        $template = $this->advanced_get($template_id, _TEMPLATES_TABLE_NAME);
-        $template->template_content = str_replace('###', ';', $template->template_content);
-        $template->template_content = str_replace('___', '--', $template->template_content);
-        if (get_class($template) <> 'templates') {
-            return null;
+        if (!empty($template_id) && $template_id <> '' && $template_id <> 'empty') {
+            $template = $this->advanced_get($template_id, _TEMPLATES_TABLE_NAME);
+            $template->template_content = str_replace('###', ';', $template->template_content);
+            $template->template_content = str_replace('___', '--', $template->template_content);
+            if (get_class($template) <> 'templates') {
+                return null;
+            } else {
+                //var_dump($template);
+                return $template;
+            }
         } else {
-            //var_dump($template);
-            return $template;
+            return null;
         }
+        
     }
 
     /**
diff --git a/modules/templates/datasources/letterbox_attachment.php b/modules/templates/datasources/letterbox_attachment.php
index 56b1e40ef95f13439a280c1498b35b3cd66e7b68..19b91bcd757619c3b2f1f1073027faf5c23ee24f 100755
--- a/modules/templates/datasources/letterbox_attachment.php
+++ b/modules/templates/datasources/letterbox_attachment.php
@@ -12,237 +12,241 @@ $contacts = new contacts_v2();
 
 // Main document resource from view
 $datasources['res_letterbox'] = array();
+if (empty($res_view)) {
+    $res_view = 'res_view_letterbox';
+}
 
-$stmt = $dbDatasource->query("SELECT * FROM " . $res_view . " WHERE res_id = ? ", array($res_id));
-$doc = $stmt->fetch(PDO::FETCH_ASSOC);
-$date = new DateTime($doc['doc_date']);
-$doc['doc_date']=$date->format('d/m/Y');
+if (!empty($res_id)) {
+        $stmt = $dbDatasource->query("SELECT * FROM " . $res_view . " WHERE res_id = ? ", array($res_id));
+        $doc = $stmt->fetch(PDO::FETCH_ASSOC);
+        $date = new DateTime($doc['doc_date']);
+        $doc['doc_date']=$date->format('d/m/Y');
 
-$admission_date = new DateTime($doc['admission_date']);
-$doc['admission_date']=$admission_date->format('d/m/Y');
+        $admission_date = new DateTime($doc['admission_date']);
+        $doc['admission_date']=$admission_date->format('d/m/Y');
 
-$creation_date = new DateTime($doc['creation_date']);
-$doc['creation_date']=$creation_date->format('d/m/Y');
+        $creation_date = new DateTime($doc['creation_date']);
+        $doc['creation_date']=$creation_date->format('d/m/Y');
 
-$process_limit_date = new DateTime($doc['process_limit_date']);
-$doc['process_limit_date']=$process_limit_date->format('d/m/Y');
+        $process_limit_date = new DateTime($doc['process_limit_date']);
+        $doc['process_limit_date']=$process_limit_date->format('d/m/Y');
 
-$doc['category_id'] = html_entity_decode($_SESSION['coll_categories']['letterbox_coll'][$doc['category_id']]);
+        $doc['category_id'] = html_entity_decode($_SESSION['coll_categories']['letterbox_coll'][$doc['category_id']]);
 
-$doc['nature_id'] = $_SESSION['mail_natures'][$doc['nature_id']];
+        $doc['nature_id'] = $_SESSION['mail_natures'][$doc['nature_id']];
 
 
-//INITIATOR INFO OF DOCUMENT
-$stmt2 = $dbDatasource->query("SELECT * FROM entities WHERE entity_id = ? ", array($doc['initiator']));
-$initiator = $stmt2->fetch(PDO::FETCH_ASSOC);
+    //INITIATOR INFO OF DOCUMENT
+    $stmt2 = $dbDatasource->query("SELECT * FROM entities WHERE entity_id = ? ", array($doc['initiator']));
+    $initiator = $stmt2->fetch(PDO::FETCH_ASSOC);
 
-if (!empty($initiator)) {
-    foreach ($initiator as $column => $value) {
-        
-        $doc['initiator_'.$column] = $value;
+    if (!empty($initiator)) {
+        foreach ($initiator as $column => $value) {
+            
+            $doc['initiator_'.$column] = $value;
+        }
     }
-}
 
-$datasources['res_letterbox'][] = $doc;
+    $datasources['res_letterbox'][] = $doc;
 
-//COMPLEMENTARY CURRENT USER INFO
-$stmt2 = $dbDatasource->query("SELECT * FROM entities WHERE entity_id = ? ", array($_SESSION['user']['primaryentity']['id']));
-$dest = $stmt2->fetch(PDO::FETCH_ASSOC);
+    //COMPLEMENTARY CURRENT USER INFO
+    $stmt2 = $dbDatasource->query("SELECT * FROM entities WHERE entity_id = ? ", array($_SESSION['user']['primaryentity']['id']));
+    $dest = $stmt2->fetch(PDO::FETCH_ASSOC);
 
-if (!empty($dest)) {
-    foreach ($dest as $column => $value) {     
-        $datasources['user'][0][$column] = $value;
+    if (!empty($dest)) {
+        foreach ($dest as $column => $value) {     
+            $datasources['user'][0][$column] = $value;
+        }
     }
-}
 
 
-//multicontact
-$stmt = $dbDatasource->query("SELECT * FROM contacts_res WHERE res_id = ? AND contact_id = ? ", array($doc['res_id'], $res_contact_id));
-$datasources['res_letterbox_contact'][] = $stmt->fetch(PDO::FETCH_ASSOC);
-
-if ($datasources['res_letterbox_contact'][0]['contact_id'] <> '') {
-        // $datasources['contact'] = array();
-    $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ? ", array($datasources['res_letterbox_contact'][0]['contact_id'], $datasources['res_letterbox_contact'][0]['address_id']));
-    $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
-    $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
-    $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
-    $datasources['contact'][] = $myContact;
-
-    // single Contact
-} else if (isset($res_contact_id) && isset($res_address_id) && is_numeric($res_contact_id)) {
-    $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ? ", array($res_contact_id, $res_address_id));
-    $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
-    $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
-    $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
-    $datasources['contact'][] = $myContact;
-    
-} else if (!empty($res_contact_id) && !is_numeric($res_contact_id)) {
-    $stmt = $dbDatasource->query("SELECT firstname, lastname, user_id, mail, phone, initials FROM users WHERE user_id = ?", [$res_contact_id]);
-    $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
-    $datasources['contact'][] = $myContact;
-
-} else {
-    $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ?" , array($datasources['res_letterbox'][0]['contact_id'],$datasources['res_letterbox'][0]['address_id']));
-    $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
-    $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
-    $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
-    $datasources['contact'][] = $myContact;
-}
+    //multicontact
+    $stmt = $dbDatasource->query("SELECT * FROM contacts_res WHERE res_id = ? AND contact_id = ? ", array($doc['res_id'], $res_contact_id));
+    $datasources['res_letterbox_contact'][] = $stmt->fetch(PDO::FETCH_ASSOC);
+
+    if ($datasources['res_letterbox_contact'][0]['contact_id'] <> '') {
+            // $datasources['contact'] = array();
+        $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ? ", array($datasources['res_letterbox_contact'][0]['contact_id'], $datasources['res_letterbox_contact'][0]['address_id']));
+        $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
+        $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
+        $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
+        $datasources['contact'][] = $myContact;
+
+        // single Contact
+    } else if (isset($res_contact_id) && isset($res_address_id) && is_numeric($res_contact_id)) {
+        $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ? ", array($res_contact_id, $res_address_id));
+        $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
+        $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
+        $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
+        $datasources['contact'][] = $myContact;
+        
+    } else if (!empty($res_contact_id) && !is_numeric($res_contact_id)) {
+        $stmt = $dbDatasource->query("SELECT firstname, lastname, user_id, mail, phone, initials FROM users WHERE user_id = ?", [$res_contact_id]);
+        $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
+        $datasources['contact'][] = $myContact;
 
-if (isset($datasources['contact'][0]['title']) && $datasources['contact'][0]['title'] == '')
-    $datasources['contact'][0]['title'] = $datasources['contact'][0]['contact_title'];
-if (isset($datasources['contact'][0]['firstname']) && $datasources['contact'][0]['firstname'] == '')
-    $datasources['contact'][0]['firstname'] = $datasources['contact'][0]['contact_firstname'];
-if (isset($datasources['contact'][0]['lastname']) && $datasources['contact'][0]['lastname'] == '')
-    $datasources['contact'][0]['lastname'] = $datasources['contact'][0]['contact_lastname'];
-if (isset($datasources['contact'][0]['function']) && $datasources['contact'][0]['function'] == '')
-    $datasources['contact'][0]['function'] = $datasources['contact'][0]['contact_function'];
-if (isset($datasources['contact'][0]['other_data']) && $datasources['contact'][0]['other_data'] == '')
-    $datasources['contact'][0]['other_data'] = $datasources['contact'][0]['contact_other_data'];
-
-// Notes
-$datasources['notes'] = array();
-$stmt = $dbDatasource->query("SELECT notes.*, users.firstname, users.lastname FROM notes left join users on notes.user_id = users.user_id WHERE coll_id = ? AND identifier = ?", array($coll_id, $res_id));
-
-$countNote = 1;
-while ($notes = $stmt->fetchObject()) {
-    $datasources['notes'][0]['note_text' . $countNote] = $notes->note_text;
-    $datasources['notes'][0]['date_note' . $countNote] = $notes->date_note;
-    $countNote++;
-}
+    } else {
+        $stmt = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? and ca_id = ?" , array($datasources['res_letterbox'][0]['contact_id'],$datasources['res_letterbox'][0]['address_id']));
+        $myContact = $stmt->fetch(PDO::FETCH_ASSOC);
+        $myContact['contact_title'] = $contacts->get_civility_contact($myContact['contact_title']);
+        $myContact['title'] = $contacts->get_civility_contact($myContact['title']);
+        $datasources['contact'][] = $myContact;
+    }
 
+    if (isset($datasources['contact'][0]['title']) && $datasources['contact'][0]['title'] == '')
+        $datasources['contact'][0]['title'] = $datasources['contact'][0]['contact_title'];
+    if (isset($datasources['contact'][0]['firstname']) && $datasources['contact'][0]['firstname'] == '')
+        $datasources['contact'][0]['firstname'] = $datasources['contact'][0]['contact_firstname'];
+    if (isset($datasources['contact'][0]['lastname']) && $datasources['contact'][0]['lastname'] == '')
+        $datasources['contact'][0]['lastname'] = $datasources['contact'][0]['contact_lastname'];
+    if (isset($datasources['contact'][0]['function']) && $datasources['contact'][0]['function'] == '')
+        $datasources['contact'][0]['function'] = $datasources['contact'][0]['contact_function'];
+    if (isset($datasources['contact'][0]['other_data']) && $datasources['contact'][0]['other_data'] == '')
+        $datasources['contact'][0]['other_data'] = $datasources['contact'][0]['contact_other_data'];
+
+    // Notes
+    $datasources['notes'] = array();
+    $stmt = $dbDatasource->query("SELECT notes.*, users.firstname, users.lastname FROM notes left join users on notes.user_id = users.user_id WHERE coll_id = ? AND identifier = ?", array($coll_id, $res_id));
+
+    $countNote = 1;
+    while ($notes = $stmt->fetchObject()) {
+        $datasources['notes'][0]['note_text' . $countNote] = $notes->note_text;
+        $datasources['notes'][0]['date_note' . $countNote] = $notes->date_note;
+        $countNote++;
+    }
 
 
-$stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'VISA_CIRCUIT']);
-$datasources['visa']= [];
-$countVisa = 1;
-while ($visa = $stmt->fetchObject()) {
-    $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$visa->item_id]);
-    $visaContact = $stmt2->fetchObject();
-    $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$visa->item_id, 'Y']);
-    $visaEntity = $stmt3->fetchObject();
-    if ($visaContact) {
-        if ($visa->item_mode == 'sign') {
-            $datasources['visa'][0]['firstnameSign'] = $visaContact->firstname;
-            $datasources['visa'][0]['lastnameSign'] = $visaContact->lastname;
-            $datasources['visa'][0]['entitySign'] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
-        } else {
-            $datasources['visa'][0]['firstname' . $countVisa] = $visaContact->firstname;
-            $datasources['visa'][0]['lastname' . $countVisa] = $visaContact->lastname;
-            $datasources['visa'][0]['entity' . $countVisa] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
-            $countVisa++;
+
+    $stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'VISA_CIRCUIT']);
+    $datasources['visa']= [];
+    $countVisa = 1;
+    while ($visa = $stmt->fetchObject()) {
+        $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$visa->item_id]);
+        $visaContact = $stmt2->fetchObject();
+        $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$visa->item_id, 'Y']);
+        $visaEntity = $stmt3->fetchObject();
+        if ($visaContact) {
+            if ($visa->item_mode == 'sign') {
+                $datasources['visa'][0]['firstnameSign'] = $visaContact->firstname;
+                $datasources['visa'][0]['lastnameSign'] = $visaContact->lastname;
+                $datasources['visa'][0]['entitySign'] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
+            } else {
+                $datasources['visa'][0]['firstname' . $countVisa] = $visaContact->firstname;
+                $datasources['visa'][0]['lastname' . $countVisa] = $visaContact->lastname;
+                $datasources['visa'][0]['entity' . $countVisa] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
+                $countVisa++;
+            }
         }
-    }
 
-}
+    }
 
 
 
 
-//sleep(10);
-// Attachments
-$datasources['attachments'] = array();
-$myAttachment['chrono'] = $chronoAttachment;
+    //sleep(10);
+    // Attachments
+    $datasources['attachments'] = array();
+    $myAttachment['chrono'] = $chronoAttachment;
 
-//thirds
-$stmt = $dbDatasource->query("SELECT * FROM contacts_res WHERE res_id = ? AND mode = ? ", [$doc['res_id'], 'third']);
-$datasources['thirds']= [];
-$countThird = 1;
-while ($third = $stmt->fetchObject()) {
-    if (is_numeric($third->contact_id)) {
-        $stmt2 = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? ", [$third->contact_id]);
-        $thirdContact = $stmt2->fetchObject();
-        if ($thirdContact) {
-            $datasources['thirds'][0]['firstname' . $countThird] = ($thirdContact->contact_firstname ?: $thirdContact->firstname);
-            $datasources['thirds'][0]['lastname' . $countThird] = ($thirdContact->contact_lastname ?: $thirdContact->lastname);
-        }
-    } else {
-        $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$third->contact_id]);
-        $thirdContact = $stmt2->fetchObject();
-        if ($thirdContact) {
-            $datasources['thirds'][0]['firstname' . $countThird] = $thirdContact->firstname;
-            $datasources['thirds'][0]['lastname' . $countThird] = $thirdContact->lastname;
+    //thirds
+    $stmt = $dbDatasource->query("SELECT * FROM contacts_res WHERE res_id = ? AND mode = ? ", [$doc['res_id'], 'third']);
+    $datasources['thirds']= [];
+    $countThird = 1;
+    while ($third = $stmt->fetchObject()) {
+        if (is_numeric($third->contact_id)) {
+            $stmt2 = $dbDatasource->query("SELECT * FROM view_contacts WHERE contact_id = ? ", [$third->contact_id]);
+            $thirdContact = $stmt2->fetchObject();
+            if ($thirdContact) {
+                $datasources['thirds'][0]['firstname' . $countThird] = ($thirdContact->contact_firstname ?: $thirdContact->firstname);
+                $datasources['thirds'][0]['lastname' . $countThird] = ($thirdContact->contact_lastname ?: $thirdContact->lastname);
+            }
+        } else {
+            $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$third->contact_id]);
+            $thirdContact = $stmt2->fetchObject();
+            if ($thirdContact) {
+                $datasources['thirds'][0]['firstname' . $countThird] = $thirdContact->firstname;
+                $datasources['thirds'][0]['lastname' . $countThird] = $thirdContact->lastname;
+            }
         }
+        $countThird++;
     }
-    $countThird++;
-}
 
-//visa
-$stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'VISA_CIRCUIT']);
-$datasources['visa']= [];
-$countVisa = 1;
-while ($visa = $stmt->fetchObject()) {
-    $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$visa->item_id]);
-    $visaContact = $stmt2->fetchObject();
-    $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$visa->item_id, 'Y']);
-    $visaEntity = $stmt3->fetchObject();
-    if ($visaContact) {
-        if ($visa->item_mode == 'sign') {
-            $datasources['visa'][0]['firstnameSign'] = $visaContact->firstname;
-            $datasources['visa'][0]['lastnameSign'] = $visaContact->lastname;
-            $datasources['visa'][0]['entitySign'] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
-        } else {
-            $datasources['visa'][0]['firstname' . $countVisa] = $visaContact->firstname;
-            $datasources['visa'][0]['lastname' . $countVisa] = $visaContact->lastname;
-            $datasources['visa'][0]['entity' . $countVisa] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
-            $countVisa++;
+    //visa
+    $stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'VISA_CIRCUIT']);
+    $datasources['visa']= [];
+    $countVisa = 1;
+    while ($visa = $stmt->fetchObject()) {
+        $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$visa->item_id]);
+        $visaContact = $stmt2->fetchObject();
+        $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$visa->item_id, 'Y']);
+        $visaEntity = $stmt3->fetchObject();
+        if ($visaContact) {
+            if ($visa->item_mode == 'sign') {
+                $datasources['visa'][0]['firstnameSign'] = $visaContact->firstname;
+                $datasources['visa'][0]['lastnameSign'] = $visaContact->lastname;
+                $datasources['visa'][0]['entitySign'] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
+            } else {
+                $datasources['visa'][0]['firstname' . $countVisa] = $visaContact->firstname;
+                $datasources['visa'][0]['lastname' . $countVisa] = $visaContact->lastname;
+                $datasources['visa'][0]['entity' . $countVisa] = str_replace($visaEntity->entity_id . ': ', '', $visaEntity->entity_label);
+                $countVisa++;
+            }
         }
-    }
 
-}
+    }
 
-//AVIS CICUIT
-$stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'AVIS_CIRCUIT']);
-$datasources['avis']= [];
-$countVisa = 1;
-$i = 1;
-while ($avis = $stmt->fetchObject()) {
-    $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$avis->item_id]);
-    $avisContact = $stmt2->fetchObject();
-    $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$avis->item_id, 'Y']);
-    $stmt4 = $dbDatasource->query("SELECT note_text, date_note FROM notes WHERE user_id = ? AND identifier = ? AND note_text LIKE ? ORDER BY date_note ASC", [$avis->item_id, $doc['res_id'], '[Avis n°%']);
-
-    $avisEntity = $stmt3->fetchObject();
-    $avisContent = $stmt4->fetchObject();
-    if ($avisContact) {
-        if ($avis->item_mode == 'avis') {
-            $datasources['avis'][0]['firstname'.$i] = $avisContact->firstname;
-            $datasources['avis'][0]['lastname'.$i] = $avisContact->lastname;
-            $datasources['avis'][0]['entity'.$i] = str_replace($avisEntity->entity_id . ': ', '', $avisEntity->entity_label);
-            if ($avisContent) {
-                $datasources['avis'][0]['note'.$i] = $avisContent->note_text;
-                $datasources['avis'][0]['date_note'.$i] = $avisContent->note_text;
+    //AVIS CICUIT
+    $stmt = $dbDatasource->query("SELECT * FROM listinstance WHERE res_id = ? AND difflist_type = ?  ORDER BY sequence ASC", [$doc['res_id'], 'AVIS_CIRCUIT']);
+    $datasources['avis']= [];
+    $countVisa = 1;
+    $i = 1;
+    while ($avis = $stmt->fetchObject()) {
+        $stmt2 = $dbDatasource->query("SELECT * FROM users WHERE user_id = ? ", [$avis->item_id]);
+        $avisContact = $stmt2->fetchObject();
+        $stmt3 = $dbDatasource->query("SELECT en.entity_id, en.entity_label FROM entities en, users_entities ue WHERE ue.user_id = ? AND primary_entity = ? AND ue.entity_id = en.entity_id", [$avis->item_id, 'Y']);
+        $stmt4 = $dbDatasource->query("SELECT note_text, date_note FROM notes WHERE user_id = ? AND identifier = ? AND note_text LIKE ? ORDER BY date_note ASC", [$avis->item_id, $doc['res_id'], '[Avis n°%']);
+
+        $avisEntity = $stmt3->fetchObject();
+        $avisContent = $stmt4->fetchObject();
+        if ($avisContact) {
+            if ($avis->item_mode == 'avis') {
+                $datasources['avis'][0]['firstname'.$i] = $avisContact->firstname;
+                $datasources['avis'][0]['lastname'.$i] = $avisContact->lastname;
+                $datasources['avis'][0]['entity'.$i] = str_replace($avisEntity->entity_id . ': ', '', $avisEntity->entity_label);
+                if ($avisContent) {
+                    $datasources['avis'][0]['note'.$i] = $avisContent->note_text;
+                    $datasources['avis'][0]['date_note'.$i] = $avisContent->note_text;
+                }
+                
             }
-            
         }
+        $i++;
     }
-    $i++;
-}
 
-// Transmissions
-$datasources['transmissions'] = [];
-if (isset($_SESSION['transmissionContacts'])) {
-
-    if (isset($_SESSION['upfileTransmissionNumber']) && $_SESSION['transmissionContacts'][$_SESSION['upfileTransmissionNumber']]) {
-        $curNb = $_SESSION['upfileTransmissionNumber'];
-        foreach ($_SESSION['transmissionContacts'][$curNb] as $key => $value) {
-            if ($key == 'title')
-                $datasources['transmissions'][0]['currentContact_' . $key] = $contacts->get_civility_contact($value);
-            else
-                $datasources['transmissions'][0]['currentContact_' . $key] = $value;
+    // Transmissions
+    $datasources['transmissions'] = [];
+    if (isset($_SESSION['transmissionContacts'])) {
+
+        if (isset($_SESSION['upfileTransmissionNumber']) && $_SESSION['transmissionContacts'][$_SESSION['upfileTransmissionNumber']]) {
+            $curNb = $_SESSION['upfileTransmissionNumber'];
+            foreach ($_SESSION['transmissionContacts'][$curNb] as $key => $value) {
+                if ($key == 'title')
+                    $datasources['transmissions'][0]['currentContact_' . $key] = $contacts->get_civility_contact($value);
+                else
+                    $datasources['transmissions'][0]['currentContact_' . $key] = $value;
+            }
         }
-    }
 
-    for ($nb = 1; $_SESSION['transmissionContacts'][$nb]; $nb++) {
-        foreach ($_SESSION['transmissionContacts'][$nb] as $key => $value) {
-            if ($key == 'title')
-                $datasources['transmissions'][0][$key . $nb] = $contacts->get_civility_contact($value);
-            else
-                $datasources['transmissions'][0][$key . $nb] = $value;
+        for ($nb = 1; $_SESSION['transmissionContacts'][$nb]; $nb++) {
+            foreach ($_SESSION['transmissionContacts'][$nb] as $key => $value) {
+                if ($key == 'title')
+                    $datasources['transmissions'][0][$key . $nb] = $contacts->get_civility_contact($value);
+                else
+                    $datasources['transmissions'][0][$key . $nb] = $value;
+            }
         }
     }
 }
-
 $img_file_name = $_SESSION['config']['tmppath'].$_SESSION['user']['UserId'].time().rand()."_barcode_attachment.png";
 
 require_once 'apps/maarch_entreprise/tools/pdfb/barcode/pi_barcode.php';