From c2123e8fa8acd4dc0a80f18094a7c0e4030631f3 Mon Sep 17 00:00:00 2001
From: Florian Azizian <florian.azizian@maarch.org>
Date: Tue, 3 Mar 2015 16:35:11 +0000
Subject: [PATCH] FEAT #1436 new version for attachments

---
 attachments/trunk/attachments_content.php    | 992 +++++++++++++++++++
 attachments/trunk/choose_attachment.php      | 106 ++
 attachments/trunk/del_attachment.php         |  64 +-
 attachments/trunk/frame_list_attachments.php | 421 +++++---
 attachments/trunk/js/functions.js            | 151 +++
 attachments/trunk/lang/fr.php                |  61 ++
 attachments/trunk/previous_attachments.php   | 133 +++
 attachments/trunk/setFinalVersion.php        |  55 +
 attachments/trunk/view_attachment.php        |  14 +-
 attachments/trunk/xml/services.xml           |  26 +-
 10 files changed, 1873 insertions(+), 150 deletions(-)
 create mode 100644 attachments/trunk/attachments_content.php
 create mode 100644 attachments/trunk/choose_attachment.php
 create mode 100644 attachments/trunk/previous_attachments.php
 create mode 100644 attachments/trunk/setFinalVersion.php

diff --git a/attachments/trunk/attachments_content.php b/attachments/trunk/attachments_content.php
new file mode 100644
index 00000000000..7a91f5d92ef
--- /dev/null
+++ b/attachments/trunk/attachments_content.php
@@ -0,0 +1,992 @@
+<?php
+/**
+* File : attachments_content.php
+*
+* Add an answer in the process
+*
+* @package Maarch 1.5
+* @since 11/2014
+* @license GPL
+* @author <dev@maarch.org>
+*/
+
+require_once "core/class/class_security.php";
+require_once "core/class/class_request.php";
+require_once "core/class/class_resource.php";
+require_once "apps" . DIRECTORY_SEPARATOR . $_SESSION['config']['app_id']
+    . DIRECTORY_SEPARATOR . "class" . DIRECTORY_SEPARATOR
+    . "class_indexing_searching_app.php";
+require_once "core/class/docservers_controler.php";
+require_once 'modules/attachments/attachments_tables.php';
+require_once "core/class/class_history.php";
+
+$core = new core_tools();
+$core->load_lang();
+$sec = new security();
+$func = new functions();
+$req = new request();
+$docserverControler = new docservers_controler();
+
+$req->connect();
+
+$_SESSION['error'] = "";
+
+$status = 0;
+$error = $content = $js = $parameters = '';
+
+function _parse($text) {
+    $text = str_replace("\r\n", "\n", $text);
+    $text = str_replace("\r", "\n", $text);
+    $text = str_replace("\n", "\\n ", $text);
+    return $text;
+}
+
+if (isset($_POST['add']) && $_POST['add']) {
+
+    if (empty($_SESSION['upfile']['tmp_name'])) {
+        $_SESSION['error'] .= _FILE_MISSING . ". ";
+    } elseif ($_SESSION['upfile']['size'] == 0) {
+        $_SESSION['error'] .= _FILE_EMPTY . ". ";
+    }
+
+    if ($_SESSION['upfile']['error'] == 1) {
+        $filesize = $func->return_bytes(ini_get("upload_max_filesize"));
+        $_SESSION['error'] = _ERROR_FILE_UPLOAD_MAX . "(" . round(
+            $filesize / 1024, 2
+        ) . "Ko Max).<br />";
+    }
+
+    $attachment_types = '';
+    if (! isset($_REQUEST['attachment_types']) || empty($_REQUEST['attachment_types'])) {
+        $_SESSION['error'] .= _ATTACHMENT_TYPES . ' ' . _MANDATORY . ". ";
+    } else {
+        $attachment_types = $func->protect_string_db($_REQUEST['attachment_types']);
+    }
+
+    $title = '';
+    if (! isset($_REQUEST['title']) || empty($_REQUEST['title'])) {
+        $_SESSION['error'] .= _OBJECT . ' ' . _MANDATORY . ". ";
+    } else {
+        $title = $func->protect_string_db($_REQUEST['title']);
+    }
+    
+    if (empty($_SESSION['error'])) {
+        require_once 'core/docservers_tools.php';
+        $arrayIsAllowed = array();
+        $arrayIsAllowed = Ds_isFileTypeAllowed(
+            $_SESSION['config']['tmppath'] . $_SESSION['upfile']['fileNameOnTmp']
+        );
+        if ($arrayIsAllowed['status'] == false) {
+            $_SESSION['error'] = _WRONG_FILE_TYPE
+                . ' ' . $arrayIsAllowed['mime_type'];
+            $_SESSION['upfile'] = array();
+        } else {
+            if (! isset($_SESSION['collection_id_choice'])
+                || empty($_SESSION['collection_id_choice'])
+            ) {
+                $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
+            }
+
+            $docserver = $docserverControler->getDocserverToInsert(
+                $_SESSION['collection_id_choice']
+            );
+            if (empty($docserver)) {
+                $_SESSION['error'] = _DOCSERVER_ERROR . ' : '
+                    . _NO_AVAILABLE_DOCSERVER . ". " . _MORE_INFOS . ".";
+                $location = "";
+            } else {
+                // some checking on docserver size limit
+                $newSize = $docserverControler->checkSize(
+                    $docserver, $_SESSION['upfile']['size']
+                );
+                if ($newSize == 0) {
+                    $_SESSION['error'] = _DOCSERVER_ERROR . ' : '
+                        . _NOT_ENOUGH_DISK_SPACE . ". " . _MORE_INFOS . ".";
+                    ?>
+                    <script type="text/javascript">
+                        var eleframe1 =  window.parent.top.document.getElementById('list_attach');
+                        eleframe1.location.href = '<?php
+                    echo $_SESSION['config']['businessappurl'];
+                    ?>index.php?display=true&module=attachments&page=frame_list_attachments&mode=normal&load';
+                    </script>
+                    <?php
+                    exit();
+                } else {
+                    $fileInfos = array(
+                        "tmpDir"      => $_SESSION['config']['tmppath'],
+                        "size"        => $_SESSION['upfile']['size'],
+                        "format"      => $_SESSION['upfile']['format'],
+                        "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
+                    );
+
+                    $storeResult = array();
+                    $storeResult = $docserverControler->storeResourceOnDocserver(
+                        $_SESSION['collection_id_choice'], $fileInfos
+                    );
+
+                    if (isset($storeResult['error']) && $storeResult['error'] <> '') {
+                        $_SESSION['error'] = $storeResult['error'];
+                    } else {
+                        $resAttach = new resource();
+                        $_SESSION['data'] = array();
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "typist",
+                                'value' => $_SESSION['user']['UserId'],
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "format",
+                                'value' => $_SESSION['upfile']['format'],
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "docserver_id",
+                                'value' => $storeResult['docserver_id'],
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "status",
+                                'value' => 'A_TRA',
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "offset_doc",
+                                'value' => ' ',
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "logical_adr",
+                                'value' => ' ',
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "title",
+                                'value' => $title,
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "attachment_type",
+                                'value' => $attachment_types,
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "coll_id",
+                                'value' => $_SESSION['collection_id_choice'],
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "res_id_master",
+                                'value' => $_SESSION['doc_id'],
+                                'type' => "integer",
+                            )
+                        );
+                        if ($_SESSION['origin'] == "scan") {
+                            array_push(
+                                $_SESSION['data'],
+                                array(
+                                    'column' => "scan_user",
+                                    'value' => $_SESSION['user']['UserId'],
+                                    'type' => "string",
+                                )
+                            );
+                            array_push(
+                                $_SESSION['data'],
+                                array(
+                                    'column' => "scan_date",
+                                    'value' => $req->current_datetime(),
+                                    'type' => "function",
+                                )
+                            );
+                        }
+                        if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> '') {
+                            array_push(
+                                $_SESSION['data'],
+                                array(
+                                    'column' => "validation_date",
+                                    'value' => $func->format_date_db($_REQUEST['back_date']),
+                                    'type' => "date",
+                                )
+                            );
+                        }
+
+                        if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] <> '') {
+                            array_push(
+                                $_SESSION['data'],
+                                array(
+                                    'column' => "dest_contact_id",
+                                    'value' => $_REQUEST['contactidAttach'],
+                                    'type' => "integer",
+                                )
+                            );
+                        }
+
+                        if (isset($_REQUEST['addressidAttach']) && $_REQUEST['addressidAttach'] <> '') {
+                            array_push(
+                                $_SESSION['data'],
+                                array(
+                                    'column' => "dest_address_id",
+                                    'value' => $_REQUEST['addressidAttach'],
+                                    'type' => "integer",
+                                )
+                            );
+                        }
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "identifier",
+                                'value' => $_REQUEST['chrono'],
+                                'type' => "string",
+                            )
+                        );
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "type_id",
+                                'value' => 0,
+                                'type' => "int",
+                            )
+                        );
+
+                        array_push(
+                            $_SESSION['data'],
+                            array(
+                                'column' => "relation",
+                                'value' => 1,
+                                'type' => "int",
+                            )
+                        );
+
+                        $id = $resAttach->load_into_db(
+                            RES_ATTACHMENTS_TABLE,
+                            $storeResult['destination_dir'],
+                            $storeResult['file_destination_name'] ,
+                            $storeResult['path_template'],
+                            $storeResult['docserver_id'], $_SESSION['data'],
+                            $_SESSION['config']['databasetype']
+                        );
+						
+						//copie de la version PDF de la pièce si mode de conversion sur le client
+						if ($_SESSION['modules_loaded']['attachments']['convertPdf'] == "client" && $_SESSION['upfile']['fileNamePdfOnTmp'] != ''){
+							$file = $_SESSION['config']['tmppath'].$_SESSION['upfile']['fileNamePdfOnTmp'];
+							$newfile = $storeResult['path_template'].str_replace('#',"/",$storeResult['destination_dir']).substr ($storeResult['file_destination_name'], 0, strrpos  ($storeResult['file_destination_name'], "." )).".pdf";
+							
+							copy($file, $newfile);
+						}
+						
+                        if ($id == false) {
+                            $_SESSION['error'] = $resAttach->get_error();
+                        } else {
+                            if ($_SESSION['history']['attachadd'] == "true") {
+                                $hist = new history();
+                                $view = $sec->retrieve_view_from_coll_id(
+                                    $_SESSION['collection_id_choice']
+                                );
+                                $hist->add(
+                                    $view, $_SESSION['doc_id'], "ADD", 'attachadd',
+                                    ucfirst(_DOC_NUM) . $id . ' '
+                                    . _NEW_ATTACH_ADDED . ' ' . _TO_MASTER_DOCUMENT
+                                    . $_SESSION['doc_id'],
+                                    $_SESSION['config']['databasetype'],
+                                    'apps'
+                                );
+                                $_SESSION['info'] = _NEW_ATTACH_ADDED;
+                                $hist->add(
+                                    RES_ATTACHMENTS_TABLE, $id, "ADD",'attachadd',
+                                    $_SESSION['info'] . " (" . $title
+                                    . ") ",
+                                    $_SESSION['config']['databasetype'],
+                                    'attachments'
+                                );
+                            }
+                        }
+                    }
+                }
+            }
+            
+            if ( empty($_SESSION['error']) || $_SESSION['error'] == _NEW_ATTACH_ADDED ) {
+                $new_nb_attach = 0;
+                $req->connect();
+                $req->query("select res_id from "
+                    . $_SESSION['tablename']['attach_res_attachments']
+                    . " where status <> 'DEL' and res_id_master = " . $_SESSION['doc_id']);
+                if ($req->nb_result() > 0) {
+                    $new_nb_attach = $req->nb_result();
+                }
+                if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'create') {
+                    $js .= "window.parent.top.location.reload()";
+                } else {
+                    $js .= 'var eleframe1 =  window.parent.top.document.getElementById(\'list_attach\');';
+                    $js .= 'eleframe1.src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load\';';
+                    $js .= 'var nb_attach = '. $new_nb_attach.';';
+                    $js .= 'window.parent.top.document.getElementById(\'nb_attach\').innerHTML = nb_attach;';
+                }
+            } else {
+                $error = $_SESSION['error'];
+                $status = 1;
+            }
+        }
+    } else {
+        $error = $_SESSION['error'];
+        $status = 1;
+    }
+    echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', error : '" . addslashes($error) . "', exec_js : '".addslashes($js)."'}";
+    exit();
+} else if (isset($_POST['edit']) && $_POST['edit']) {
+    $title = '';
+
+    if (!isset($_REQUEST['title']) || empty($_REQUEST['title'])) {
+        $_SESSION['error'] .= _OBJECT . ' ' . _MANDATORY . ". ";
+        $status = 1;
+    } else {
+        $title = $func->protect_string_db($_REQUEST['title']);
+    }
+
+    if ($status <> 1) {
+        if ($_REQUEST['new_version'] == "yes") {
+
+            if ((int)$_REQUEST['relation'] > 1) {
+                $column_res = 'res_id_version';
+            } else {
+                $column_res = 'res_id';
+            }
+
+            $req->query("SELECT attachment_type, identifier, relation, attachment_id_master 
+                            FROM res_view_attachments 
+                            WHERE ".$column_res." = ".$_REQUEST['res_id']." and res_id_master = ".$_SESSION['doc_id']."
+                            ORDER BY relation desc");
+            $previous_attachment = $req->fetch_object();
+
+            $fileInfos = array(
+                "tmpDir"      => $_SESSION['config']['tmppath'],
+                "size"        => $_SESSION['upfile']['size'],
+                "format"      => $_SESSION['upfile']['format'],
+                "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
+            );
+
+            $storeResult = array();
+            $storeResult = $docserverControler->storeResourceOnDocserver(
+                $_SESSION['collection_id_choice'], $fileInfos
+            );
+
+            if (isset($storeResult['error']) && $storeResult['error'] <> '') {
+                $_SESSION['error'] = $storeResult['error'];
+            } else {
+                $resAttach = new resource();
+                $_SESSION['data'] = array();
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "typist",
+                        'value' => $_SESSION['user']['UserId'],
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "format",
+                        'value' => $_SESSION['upfile']['format'],
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "docserver_id",
+                        'value' => $storeResult['docserver_id'],
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "status",
+                        'value' => 'A_TRA',
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "offset_doc",
+                        'value' => ' ',
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "logical_adr",
+                        'value' => ' ',
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "title",
+                        'value' => $title,
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "attachment_type",
+                        'value' => $previous_attachment->attachment_type,
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "coll_id",
+                        'value' => $_SESSION['collection_id_choice'],
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "res_id_master",
+                        'value' => $_SESSION['doc_id'],
+                        'type' => "integer",
+                    )
+                );
+                if ((int)$previous_attachment->attachment_id_master == 0) {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "attachment_id_master",
+                            'value' => $_REQUEST['res_id'],
+                            'type' => "integer",
+                        )
+                    );
+                } else {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "attachment_id_master",
+                            'value' => (int)$previous_attachment->attachment_id_master,
+                            'type' => "integer",
+                        )
+                    );                    
+                }
+
+                if ($_SESSION['origin'] == "scan") {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "scan_user",
+                            'value' => $_SESSION['user']['UserId'],
+                            'type' => "string",
+                        )
+                    );
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "scan_date",
+                            'value' => $req->current_datetime(),
+                            'type' => "function",
+                        )
+                    );
+                }
+                if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> '') {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "validation_date",
+                            'value' => $func->format_date_db($_REQUEST['back_date']),
+                            'type' => "date",
+                        )
+                    );
+                }
+
+                if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] <> '') {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "dest_contact_id",
+                            'value' => $_REQUEST['contactidAttach'],
+                            'type' => "integer",
+                        )
+                    );
+                }
+
+                if (isset($_REQUEST['addressidAttach']) && $_REQUEST['addressidAttach'] <> '') {
+                    array_push(
+                        $_SESSION['data'],
+                        array(
+                            'column' => "dest_address_id",
+                            'value' => $_REQUEST['addressidAttach'],
+                            'type' => "integer",
+                        )
+                    );
+                }
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "identifier",
+                        'value' => $previous_attachment->identifier,
+                        'type' => "string",
+                    )
+                );
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "type_id",
+                        'value' => 0,
+                        'type' => "int",
+                    )
+                );
+
+                $relation = (int)$previous_attachment->relation;
+                $relation++;
+
+                array_push(
+                    $_SESSION['data'],
+                    array(
+                        'column' => "relation",
+                        'value' => $relation,
+                        'type' => "int",
+                    )
+                );
+
+                $id = $resAttach->load_into_db(
+                    'res_version_attachments',
+                    $storeResult['destination_dir'],
+                    $storeResult['file_destination_name'] ,
+                    $storeResult['path_template'],
+                    $storeResult['docserver_id'], $_SESSION['data'],
+                    $_SESSION['config']['databasetype']
+                );
+                $req->connect();
+                if ($previous_attachment->relation == 1) {
+                    $req->query("UPDATE res_attachments set status = 'OBS' WHERE res_id = ".$_REQUEST['res_id']);
+                } else {
+                    $req->query("UPDATE res_version_attachments set status = 'OBS' WHERE res_id = ".$_REQUEST['res_id']);
+                }
+
+            }
+        } else {
+            $set_update = "";
+            $set_update = " title = '".$title."'";
+
+            if (isset($_REQUEST['back_date']) && $_REQUEST['back_date'] <> "") {
+                $set_update .= ", validation_date = '".$req->format_date_db($_REQUEST['back_date'])."'";
+            } else {
+                $set_update .= ", validation_date = null";
+            }
+
+            if (isset($_REQUEST['contactidAttach']) && $_REQUEST['contactidAttach'] <> "") {
+                $set_update .= ", dest_contact_id = ".$_REQUEST['contactidAttach'].", dest_address_id = ".$_REQUEST['addressidAttach'];
+            } else {
+                $set_update .= ", dest_contact_id = null, dest_address_id = null";
+            }
+
+            if ($_SESSION['upfile']['upAttachment'] == true) {
+                $fileInfos = array(
+                    "tmpDir"      => $_SESSION['config']['tmppath'],
+                    "size"        => $_SESSION['upfile']['size'],
+                    "format"      => $_SESSION['upfile']['format'],
+                    "tmpFileName" => $_SESSION['upfile']['fileNameOnTmp'],
+                );
+
+                $storeResult = array();
+                $storeResult = $docserverControler->storeResourceOnDocserver(
+                    $_SESSION['collection_id_choice'], $fileInfos
+                );
+
+                $filetmp = $storeResult['path_template'];
+                $tmp = $storeResult['destination_dir'];
+                $tmp = str_replace('#',DIRECTORY_SEPARATOR,$tmp);
+                $filetmp .= $tmp;
+                $filetmp .= $storeResult['file_destination_name'];
+                require_once 'core/class/docserver_types_controler.php';
+                require_once 'core/docservers_tools.php';
+                $docserverTypeControler = new docserver_types_controler();
+                $docserver = $docserverControler->get($storeResult['docserver_id']);
+                $docserverTypeObject = $docserverTypeControler->get($docserver->docserver_type_id);
+                $fingerprint = Ds_doFingerprint($filetmp, $docserverTypeObject->fingerprint_mode);
+                $filesize = filesize($filetmp);
+                $set_update .= ", fingerprint = '".$fingerprint."'";
+                $set_update .= ", filesize = ".$filesize;
+                $set_update .= ", path = '".$storeResult['destination_dir']."'";
+                $set_update .= ", filename = '".$storeResult['file_destination_name']."'";
+                // $set_update .= ", docserver_id = ".$storeResult['docserver_id'];
+            }
+
+            $set_update .= ", doc_date = ".$req->current_datetime().", updated_by = '".$_SESSION['user']['UserId']."'";
+
+            if (isset($storeResult['error']) && $storeResult['error'] <> '') {
+                $_SESSION['error'] = $storeResult['error'];
+            } else {
+                $req->connect();
+                if ((int)$_REQUEST['relation'] == 1) {
+                    $req->query("UPDATE res_attachments SET " . $set_update . " WHERE res_id = ".$_REQUEST['res_id']);
+                } else {
+                    $req->query("UPDATE res_version_attachments SET " . $set_update . " WHERE res_id = ".$_REQUEST['res_id']);
+                }
+            }
+            
+        }
+        
+        if ($_SESSION['history']['attachup'] == "true") {
+            $hist = new history();
+            $view = $sec->retrieve_view_from_coll_id(
+                $_SESSION['collection_id_choice']
+            );
+            $hist->add(
+                $view, $_SESSION['doc_id'], "UP", 'attachup',
+                ucfirst(_DOC_NUM) . $id . ' '
+                . _ATTACH_UPDATED,
+                $_SESSION['config']['databasetype'],
+                'apps'
+            );
+            $_SESSION['info'] = _ATTACH_UPDATED;
+            $hist->add(
+                RES_ATTACHMENTS_TABLE, $id, "UP",'attachup',
+                $_SESSION['info'] . " (" . $title
+                . ") ",
+                $_SESSION['config']['databasetype'],
+                'attachments'
+            );
+        }
+
+        if (empty($_SESSION['error'])) {
+            $js .= 'var eleframe1 =  window.top.document.getElementsByName(\'list_attach\');';
+            if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
+                $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';
+                $js .= '&attach_type_exclude=response_project,outgoing_mail_signed&fromDetail=attachments';
+            } else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response'){
+                $js .= 'eleframe1[1].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';
+                $js .= '&attach_type=response_project,outgoing_mail_signed&fromDetail=response';
+            } else {
+                $js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';
+            }
+            $js .='\';';
+        } else {
+            $error = $_SESSION['error'];
+            $status = 1;
+        }
+
+    } else {
+        $error = $_SESSION['error'];
+        $status = 1;
+    }
+
+    echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', error : '" . addslashes($error) . "', exec_js : '".addslashes($js)."'}";
+    exit();
+}
+
+if (isset($_REQUEST['id'])) {
+
+    if ((int)$_REQUEST['relation'] > 1) {
+        $column_res = 'res_id_version';
+    } else {
+        $column_res = 'res_id';
+    }
+
+    $req->connect();
+    $req->query("SELECT validation_date, title, dest_contact_id, dest_address_id, relation 
+                    FROM res_view_attachments 
+                    WHERE ".$column_res." = ".$_REQUEST['id']." and res_id_master = ".$_SESSION['doc_id']."
+                    ORDER BY relation desc");
+    $data_attachment = $req->fetch_object();
+
+    if ($data_attachment->relation == 1) {
+        $res_table = 'res_attachments';
+    } else {
+        $res_table = 'res_version_attachments';  
+    }
+
+    $viewResourceArr = $docserverControler->viewResource(
+        $_REQUEST['id'], 
+        $res_table, 
+        'adr_x', 
+        false
+    );
+
+    $_SESSION['upfile']['size'] = filesize($viewResourceArr['file_path']);
+    $_SESSION['upfile']['format'] = $viewResourceArr['ext'];
+    $fileNameOnTmp = str_replace($viewResourceArr['tmp_path'].DIRECTORY_SEPARATOR, '', $viewResourceArr['file_path']);
+    $_SESSION['upfile']['fileNameOnTmp'] = $fileNameOnTmp;
+
+} else {
+    $req->query("SELECT subject, exp_contact_id, address_id FROM res_view_letterbox WHERE res_id = ".$_SESSION['doc_id']);
+    $data_attachment = $req->fetch_object();
+
+    unset($_SESSION['upfile']);
+}
+
+if ($data_attachment->dest_contact_id <> "") {
+    $req->connect();
+    $req->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
+                    FROM view_contacts 
+                    WHERE contact_id = ' . $data_attachment->dest_contact_id . ' and ca_id = ' . $data_attachment->dest_address_id);
+} else if ($data_attachment->exp_contact_id <> "") {
+    $req->connect();
+    $req->query('SELECT is_corporate_person, is_private, contact_lastname, contact_firstname, society, society_short, address_num, address_street, address_town, lastname, firstname 
+                    FROM view_contacts 
+                    WHERE contact_id = ' . $data_attachment->exp_contact_id . ' and ca_id = ' . $data_attachment->address_id);       
+}
+
+if ($data_attachment->exp_contact_id <> '' || $data_attachment->dest_contact_id <> '') {
+    $res = $req->fetch_object();
+    if ($res->is_corporate_person == 'Y') {
+        $data_contact = $res->society;
+        if (!empty ($res->society_short)) {
+            $data_contact .= ' ('.$res->society_short.')';
+        }
+        if (!empty($res->lastname) || !empty($res->firstname)) {
+            $data_contact .= ' - ' . $res->lastname . ' ' . $res->firstname;
+        }
+        $data_contact .= ', ';
+    } else {
+        $data_contact .= $res->contact_lastname . ' ' . $res->contact_firstname;
+        if (!empty ($res->society)) {
+            $data_contact .= ' (' .$res->society . ')';
+        }
+        $data_contact .= ', ';
+    }
+    if ($res->is_private == 'Y') {
+        $data_contact .= '('._CONFIDENTIAL_ADDRESS.')';
+    } else {
+        $data_contact .= $res->address_num .' ' . $res->address_street .' ' . strtoupper($res->address_town);                         
+    }
+}
+
+$content .= '<div class="block" style="width:2000px">';
+    $content .= '<div class="error" >' . $_SESSION['error'];
+    $_SESSION['error'] = "";
+
+//require 'modules/templates/class/templates_controler.php';
+//$templatesControler = new templates_controler();
+//$templates = array();
+//$templates = $templatesControler->getAllTemplatesForProcess($_SESSION['destination_entity']);
+$objectTable = $sec->retrieve_table_from_coll($_SESSION['collection_id_choice']);
+    $content .= '</div>';
+    $content .= '<br/>';
+
+    if (isset($_REQUEST['id'])) {
+        $title = _MODIFY_ANSWER;
+    } else {
+        $title = _ATTACH_ANSWER;        
+    }
+    $content .= '<h2 class="tit" style="margin-bottom:-10px">&nbsp;' . $title . '</h2>'; 
+
+    $content .= '<form enctype="multipart/form-data" method="post" name="formAttachment" id="formAttachment" action="#" class="forms" style="width:30%;height:550px;float:left;margin-left:-5px;background-color:#deedf3">';
+    $content .= '<hr style="width:85%;margin-left:0px">';
+        $content .= '<input type="hidden" id="category_id" value="outgoing"/>';
+    if (isset($_REQUEST['id'])) {
+        $content .= '<input type="hidden" name="res_id" id="res_id" value="'.$_REQUEST['id'].'"/>';
+        $content .= '<input type="hidden" name="relation" id="relation" value="'.$_REQUEST['relation'].'"/>';
+    }
+    $content .= '<input type="hidden" name="fromDetail" id="fromDetail" value="'.$_REQUEST['fromDetail'].'"/>';
+
+    if (!isset($_REQUEST['id'])) {
+        $content .= '<p>';
+            $content .= '<label>' . _ATTACHMENT_TYPES . '</label>';
+            $content .= '<select name="attachment_types" id="attachment_types" onchange="affiche_chrono();select_template(\'' . $_SESSION['config']['businessappurl']
+                . 'index.php?display=true&module=templates&page='
+                . 'select_templates\', this.options[this.selectedIndex].value)"/>';
+                $content .= '<option value="">' . _CHOOSE_ATTACHMENT_TYPE . '</option>';
+                    foreach(array_keys($_SESSION['attachment_types']) as $attachmentType) {
+                        $content .= '<option value="' . $attachmentType . '" with_chrono = "'. $_SESSION['attachment_types_attribute'][$attachmentType].'">';
+                            $content .= $_SESSION['attachment_types'][$attachmentType];
+                        $content .= '</option>';
+                    }
+
+            $content .= '</select>&nbsp;<span class="red_asterisk" id="attachment_types_mandatory">*</span>';
+        $content .= '</p>';
+        $content .= '<br/>';
+        $content .= '<p>';
+            $content .= '<label id="chrono_label" style="display:none">'. _CHRONO_NUMBER.'</label>';
+            $content .= '<input type="text" name="chrono" id="chrono" style="display:none"/>';
+        $content .= '</p>';
+        $content .= '<br/>';
+        $content .= '<p>';
+            $content .= '<label>'. _MODEL.'</label>';
+            $content .= '<select name="templateOffice" id="templateOffice" onchange="showEditButton();">';
+                $content .= '<option value="">'. _CHOOSE_MODEL.'</option>';
+/*                    for ($i=0;$i<count($templates);$i++) {
+                        if ($templates[$i]['TYPE'] == 'OFFICE' && ($templates[$i]['TARGET'] == 'attachments' || $templates[$i]['TARGET'] == '')) {
+                           $content .= '<option value="'. $templates[$i]['ID'].'">';
+                            $content .= $templates[$i]['LABEL'];
+                        }
+                        $content .= '</option>';
+                    }*/
+            $content .= '</select>&nbsp;<span class="red_asterisk" id="templateOffice_mandatory">*</span>';
+        $content .= '</p>';
+        $content .= '<br/>';
+        $content .= '<p>';
+            $content .= '<label>&nbsp;</label>';
+            $content .=  _OR;
+        $content .= '</p>';
+        $content .= '<br/>';
+        $content .= '<p>';
+            $content .= '<label>'. _ATTACH_FILE.'</label>';
+            $content .= '<iframe style="width:210px" name="choose_file" id="choose_file" frameborder="0" scrolling="no" height="25" src="' . $_SESSION['config']['businessappurl']
+                            . 'index.php?display=true&module=attachments&page=choose_attachment"></iframe>';
+            $content .= '<input type="text" name="not_enabled" id="not_enabled" disabled value="'. _ALREADY_MODEL_SELECTED.'" style="display:none" />';
+            $content .= '<img id="file_loaded" style="display:none;margin-top:-15px" src="'. $_SESSION['config']['businessappurl'].'static.php?filename=picto_stat_enabled.gif" />';
+        $content .= '</p>';
+        $content .= '<br/>';
+    }
+        $content .= '<p>';
+            $content .= '<label>'. _OBJECT .'</label>';
+            $content .= '<input type="text" name="title" id="title" value="';
+            if (isset($_REQUEST['id'])) {
+                $content .= $req->show_string($data_attachment->title);
+            } else {
+                $content .= $req->show_string($data_attachment->subject);
+            }
+            $content .= '"/>&nbsp;<span class="red_asterisk" id="templateOffice_mandatory">*</span>';
+        $content .= '</p>';
+        if (!isset($_REQUEST['id'])) {
+            $content .= '<hr style="width:85%;margin-left:0px">';
+        } else {
+            $content .= '<br/>';
+        }
+        $content .= '<p>';
+            $content .= '<label>'. _BACK_DATE.'</label>';
+            $content .= '<input type="text" name="back_date" id="back_date" onClick="showCalender(this);" value="';
+            if (isset($_REQUEST['id'])) {
+                $content .= $req->format_date_db($data_attachment->validation_date);
+            }
+
+            $content .='"/>';
+        $content .= '</p>';
+        $content .= '<br/>';
+        $content .= '<p>';
+            $content .= '<label>'. _DEST_USER;
+            if ($core->test_admin('my_contacts', 'apps', false)) {
+                $content .= ' <a href="#" id="create_multi_contact" title="' . _CREATE_CONTACT
+                        . '" onclick="new Effect.toggle(\'create_contact_div_attach\', '
+                        . '\'blind\', {delay:0.2});return false;" '
+                        . 'style="display:inline;" ><img src="'
+                        . $_SESSION['config']['businessappurl'] . 'static.php?filename='
+                        . 'modif_liste.png" alt="' . _CREATE_CONTACT . '"/></a>';
+            }
+           $content .='<a href="#" id="contact_card_attach" title="'._CONTACT_CARD.'" onclick="document.getElementById(\'info_contact_iframe_attach\').src=\'' . $_SESSION['config']['businessappurl']
+                . 'index.php?display=false&dir=my_contacts&page=info_contact_iframe&contactid=\'+document.getElementById(\'contactidAttach\').value+\'&addressid=\'+document.getElementById(\'addressidAttach\').value+\'&fromAttachmentContact=Y\';new Effect.toggle(\'info_contact_div_attach\', '
+                . '\'blind\', {delay:0.2});return false;"'
+                . ' style="visibility:hidden;padding-left:35%"><img src="'.$_SESSION['config']['businessappurl'].'static.php?filename=my_contacts_off.gif" alt="'._CONTACT_CARD.'" /></a>';
+            $content .= '</label>';
+            $content .= '<input type="text" name="contact_attach" onblur="display_contact_card(\'visible\', \'contact_card_attach\');" onkeyup="erase_contact_external_id(\'contact_attach\', \'contactidAttach\');erase_contact_external_id(\'contact_attach\', \'addressidAttach\');" id="contact_attach" value="';
+                $content .= $data_contact;
+            $content .= '"/>';
+            $content .= '<div id="show_contacts_attach" class="autocomplete autocompleteIndex"></div>';
+        $content .= '</p>';
+        $content .= '<input type="hidden" id="contactidAttach" name="contactidAttach" value="';
+                if (isset($_REQUEST['id'])) {
+                    $content .= $data_attachment->dest_contact_id;
+                } else if ($data_attachment->exp_contact_id){
+                    $content .= $data_attachment->exp_contact_id;
+                }
+        $content .= '"/>';
+        $content .= '<input type="hidden" id="addressidAttach" name="addressidAttach" value="';
+            if (isset($_REQUEST['id'])) {
+                $content .= $data_attachment->dest_address_id;
+            } else if ($data_attachment->address_id <> ''){
+                $content .= $data_attachment->address_id;
+            }
+        $content .= '"/>';
+        $content .= '<br/>';
+    if (isset($_REQUEST['id'])) {
+         $content .= '<p>';
+            $content .= '<label>'. _CREATE_NEW_ATTACHMENT_VERSION.'</label>';
+            $content .= '<input type="radio" name="new_version" id="new_version_yes" value="yes"/>'._YES;
+            $content .= '&nbsp;&nbsp;';
+            $content .= '<input type="radio" name="new_version" id="new_version_no" checked value="no"/>'._NO;
+        $content .= '</p>';
+        $content .= '<br/>';   
+    }
+        $content .= '<p class="buttons">';
+            $content .= '<input type="button" value="';
+                $content .=  _VALIDATE;
+                if (isset($_REQUEST['id'])) {
+                    $content .= '" name="edit" id="edit" class="button" onclick="ValidAttachmentsForm(\'' . $_SESSION['config']['businessappurl'] ;
+                } else {
+                    $content .= '" name="add" id="add" class="button" onclick="ValidAttachmentsForm(\'' . $_SESSION['config']['businessappurl'] ;                   
+                }
+
+                $content .= 'index.php?display=true&module=attachments&page=attachments_content\', \'formAttachment\')"/>';
+                $content .= '&nbsp;';
+            $content .= '<input type="button" value="';
+                $content .=  _CANCEL;
+                $content .= '" name="cancel" class="button"  onclick="destroyModal(\'form_attachments\');"/>';
+                $content .= '&nbsp;';
+                $content .= '&nbsp;';
+            $content .= '<input type="button" value="';
+                $content .= _EDIT_MODEL;
+
+            if (isset($_REQUEST['id'])) {
+                    $content .= '" name="edit" id="edit" class="button" onclick="window.open(\''
+                                    . $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_popup_launcher&objectType=attachmentUpVersion&objectId='.$_REQUEST['id'].'&objectTable=res_view_attachments&resMaster='.$_SESSION['doc_id']
+                                    .'\', \'\', \'height=301, width=301,scrollbars=no,resizable=no,directories=no,toolbar=no\');"/>';
+            } else {
+                $content .= '" name="edit" id="edit" style="display:none" class="button" '
+                                .'onclick="window.open(\''. $_SESSION['config']['businessappurl'] . 'index.php?display=true&module=content_management&page=applet_popup_launcher&objectType=attachmentVersion&objectId=\'+$(\'templateOffice\').value+\'&objectTable='. $objectTable .'&resMaster='.$_SESSION['doc_id']
+                                .'\', \'\', \'height=301, width=301,scrollbars=no,resizable=no,directories=no,toolbar=no\');"/>';            
+            }
+
+        $content .= '</p>';
+    $content .= '</form>';
+
+    if (!isset($_REQUEST['id'])) {
+        $content .= '<script>launch_autocompleter_contacts_v2("'. $_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
+    } else {
+        $content .= '<script>launch_autocompleter2_contacts_v2("'. $_SESSION['config']['businessappurl'].'index.php?display=true&dir=indexing_searching&page=autocomplete_contacts", "contact_attach", "show_contacts_attach", "", "contactidAttach", "addressidAttach")</script>';
+    }
+
+    $content .= '<script>display_contact_card(\'visible\', \'contact_card_attach\');</script>';
+
+    // $content .= '<script>$(\'title\').value=</script>';
+
+    if ($core->test_admin('my_contacts', 'apps', false)) {
+        $content .= '<div id="create_contact_div_attach" style="display:none;float:left;width:65%;background-color:#deedf3">';
+            $content .= '<iframe width="100%" height="550" src="' . $_SESSION['config']['businessappurl']
+                    . 'index.php?display=false&dir=my_contacts&page=create_contact_iframe&fromAttachmentContact=Y" name="contact_iframe" id="contact_iframe"'
+                    . ' scrolling="auto" frameborder="0" style="display:block;">'
+                    . '</iframe>';
+        $content .= '</div>';
+    }
+    $content .= '<div id="info_contact_div_attach" style="display:none;float:left;width:70%;background-color:#deedf3">';
+        $content .= '<iframe width="100%" height="800" name="info_contact_iframe_attach" id="info_contact_iframe_attach"'
+                . ' scrolling="auto" frameborder="0" style="display:block;">'
+                . '</iframe>';
+    $content .= '</div>';
+$content .= '</div>';
+
+echo "{status : " . $status . ", content : '" . addslashes(_parse($content)) . "', error : '" . addslashes($error) . "', exec_js : '".addslashes($js)."'}";
+exit ();
\ No newline at end of file
diff --git a/attachments/trunk/choose_attachment.php b/attachments/trunk/choose_attachment.php
new file mode 100644
index 00000000000..ad9e3798038
--- /dev/null
+++ b/attachments/trunk/choose_attachment.php
@@ -0,0 +1,106 @@
+<?php
+
+/*
+*   Copyright 2008-2014 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  Frame to choose a file to index
+*
+* @file choose_attachment.php
+* @date $date$
+* @version $Revision$
+*/
+
+$core_tools = new core_tools();
+$core_tools->load_lang();
+$func = new functions();
+$db = new dbquery();
+$db->connect();
+$core_tools->load_html();
+$core_tools->load_header('', true, false);
+$upFileOK = false;
+?>
+    <body>
+    <?php
+    $_SESSION['upfile']['error'] = 0;
+    if (isset($_FILES['file']['error']) && $_FILES['file']['error'] == 1) {
+        $_SESSION['upfile']['error'] = $_FILES['file']['error'];
+        if ($_SESSION['upfile']['error'] == 1) {
+ 			$_SESSION['error'] = 'La taille du fichier telecharge excede la valeur de upload_max_filesize';
+        }
+    } elseif (!empty($_FILES['file']['tmp_name']) && $_FILES['file']['error'] <> 1) {
+    	$_SESSION['upfile']['tmp_name'] = $_FILES['file']['tmp_name'];
+        $extension = explode(".",$_FILES['file']['name']);
+        $count_level = count($extension)-1;
+        $the_ext = $extension[$count_level];
+        $fileNameOnTmp = 'tmp_file_' . $_SESSION['user']['UserId']
+            . '_' . rand() . '.' . strtolower($the_ext);
+            $_SESSION['upfile']['fileNameOnTmp'] = $fileNameOnTmp;
+        $filePathOnTmp = $_SESSION['config']['tmppath'] . $fileNameOnTmp;
+        //$md5 = md5_file($_FILES['file']['tmp_name']);
+        if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
+                $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN
+                    . ". " . _MORE_INFOS . " (<a href=\"mailto:"
+                    . $_SESSION['config']['adminmail'] . "\">"
+                    . $_SESSION['config']['adminname'] . "</a>)";
+        } elseif (!@move_uploaded_file($_FILES['file']['tmp_name'], $filePathOnTmp)) {
+            $_SESSION['error'] = _FILE_NOT_SEND . ". " . _TRY_AGAIN . ". "
+                . _MORE_INFOS . " (<a href=\"mailto:"
+                . $_SESSION['config']['adminmail'] . "\">"
+                . $_SESSION['config']['adminname'] . "</a>)";
+        } else {
+            $_SESSION['upfile']['size'] = $_FILES['file']['size'];
+            $_SESSION['upfile']['mime'] = $_FILES['file']['type'];
+            $_SESSION['upfile']['local_path'] = $filePathOnTmp;
+            //$_SESSION['upfile']['name'] = $_FILES['file']['name'];
+            $_SESSION['upfile']['name'] = $fileNameOnTmp;
+            $_SESSION['upfile']['format'] = $the_ext;
+            require_once 'core/docservers_tools.php';
+            $arrayIsAllowed = array();
+            $arrayIsAllowed = Ds_isFileTypeAllowed($_SESSION['upfile']['local_path']);
+            if ($arrayIsAllowed['status'] == false) {
+                $_SESSION['error'] = _WRONG_FILE_TYPE . ' ' . $arrayIsAllowed['mime_type'];
+                $_SESSION['upfile'] = array();
+            }
+            $upFileOK = true;
+        }
+    }
+    ?>
+    <form name="select_file_form" id="select_file_form" method="get" enctype="multipart/form-data" action="<?php
+        echo $_SESSION['config']['businessappurl'];
+        ?>index.php?display=true&module=attachments&page=choose_attachment" class="forms">
+        <input type="hidden" name="display" value="true" />
+        <input type="hidden" name="dir" value="indexing_searching" />
+        <input type="hidden" name="page" value="choose_attachment" />
+        <p>
+        <!-- window.parent.$('title').value = this.value.substring(0,this.value.indexOf('.')); -->
+            <input type="file" name="file" id="file" onchange="window.parent.$('file_loaded').setStyle({display: 'inline'});$('with_file').value='false';this.form.method = 'post';this.form.submit();" value="<?php
+                if (isset($_SESSION['file_path'])) {
+                    echo $_SESSION['file_path'];
+                } ?>" style="width:200px" />
+        </p>
+        <p style="display:none">
+            <div align="center">
+            	<input type="radio" name="with_file" id="with_file" value="false" onclick="this.form.method = 'post';this.form.submit();" />
+            </div>
+        </p>
+    </form>
+    <?php $core_tools->load_js();?>
+    </body>
+</html>
diff --git a/attachments/trunk/del_attachment.php b/attachments/trunk/del_attachment.php
index ef2eefd079c..d3c5a824183 100644
--- a/attachments/trunk/del_attachment.php
+++ b/attachments/trunk/del_attachment.php
@@ -13,10 +13,14 @@ $func = new functions();
 $db = new dbquery();
 $db->connect();
 
-$db->query(
-    "UPDATE " . RES_ATTACHMENTS_TABLE . " SET status = 'DEL' WHERE res_id = "
-    . $_REQUEST['id']
-);
+if ($_REQUEST['relation'] == 1) {
+    $db->query("UPDATE " . RES_ATTACHMENTS_TABLE . " SET status = 'DEL' WHERE res_id = " . $_REQUEST['id'] );
+} else {
+    $db->query("SELECT attachment_id_master FROM res_version_attachments WHERE res_id = " . $_REQUEST['id']);
+    $res=$db->fetch_object();
+    $db->query("UPDATE res_version_attachments SET status = 'DEL' WHERE attachment_id_master = " . $res->attachment_id_master);
+    $db->query("UPDATE res_attachments SET status = 'DEL' WHERE res_id = " . $res->attachment_id_master);
+}
 
 if ($_SESSION['history']['attachdel'] == "true") {
     $hist = new history();
@@ -27,10 +31,12 @@ if ($_SESSION['history']['attachdel'] == "true") {
     }
     $sec = new security();
     $view = $sec->retrieve_view_from_coll_id($_SESSION['collection_id_choice']);
-    $db->query(
-        "SELECT res_id_master FROM " . RES_ATTACHMENTS_TABLE
-        . " WHERE res_id = " . $_REQUEST['id']
-    );
+    if ($_REQUEST['relation'] == 1) {
+        $db->query("SELECT res_id_master FROM " . RES_ATTACHMENTS_TABLE . " WHERE res_id = " . $_REQUEST['id']);
+    } else {
+        $db->query("SELECT res_id_master FROM res_version_attachments WHERE res_id = " . $_REQUEST['id']);
+    }
+
     $res = $db->fetch_object();
     $resIdMaster = $res->res_id_master;
     $hist->add(
@@ -43,11 +49,43 @@ if ($_SESSION['history']['attachdel'] == "true") {
         . $_REQUEST['id'], $_SESSION['config']['databasetype'], "attachments"
     );
 }
+
+
+if ($_REQUEST['relation'] == 1) {
+    $db->query("SELECT res_id_master FROM " . RES_ATTACHMENTS_TABLE . " WHERE res_id = " . $_REQUEST['id']);
+} else {
+    $db->query("SELECT res_id_master FROM res_version_attachments WHERE res_id = " . $_REQUEST['id']);
+}
+
+$res = $db->fetch_object();
+$resIdMaster = $res->res_id_master;
+$query = "SELECT title FROM res_view_attachments WHERE status <> 'DEL' and status <> 'OBS' and res_id_master = " . $resIdMaster;
+    if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
+        $query .= " and (attachment_type <> 'response_project' and attachment_type <> 'outgoing_mail_signed')";
+    } else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response'){
+        $query .= " and (attachment_type = 'response_project' or attachment_type = 'outgoing_mail_signed')";
+    }
+$db->query($query);
+if ($db->nb_result() > 0) {
+    $new_nb_attach = $db->nb_result();
+} else {
+    $new_nb_attach = 0;
+}
 ?>
 <script type="text/javascript">
-    var eleframe1 =  window.top.document.getElementById('list_attach');
-    eleframe1.src = '<?php
-echo $_SESSION['config']['businessappurl'];
-?>index.php?display=true&module=attachments&page=frame_list_attachments';
-    //window.top.close();
+    var eleframe1 =  window.top.document.getElementsByName('list_attach');
+    var nb_attach = '<?php echo $new_nb_attach;?>';
+    <?php if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') { ?>
+        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type_exclude=response_project,outgoing_mail_signed&fromDetail=attachments';?>";
+        window.parent.top.document.getElementById('nb_attach').innerHTML = " ("+nb_attach+")";
+    <?php } else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response'){ ?>
+        eleframe1[1].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load&attach_type=response_project,outgoing_mail_signed&fromDetail=response';?>";
+        window.parent.top.document.getElementById('answer_number').innerHTML = " ("+nb_attach+")";
+    <?php } else { ?>
+        eleframe1[0].src = "<?php echo $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';?>";
+        window.parent.top.document.getElementById('nb_attach').innerHTML = nb_attach;
+    <?php } ?>
+
+    // window.parent.top.document.getElementById('nb_attach').innerHTML = nb_attach;
+
 </script>
diff --git a/attachments/trunk/frame_list_attachments.php b/attachments/trunk/frame_list_attachments.php
index b7b2a034e3c..03aab88bb30 100644
--- a/attachments/trunk/frame_list_attachments.php
+++ b/attachments/trunk/frame_list_attachments.php
@@ -4,7 +4,9 @@ $core = new core_tools();
 $core->load_lang();
 $core->test_service('manage_attachments', 'attachments');
 
-$func = new functions();
+require_once "apps".DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR
+            ."class".DIRECTORY_SEPARATOR."class_lists.php";
+$list       = new lists(); 
 
 if (empty($_SESSION['collection_id_choice'])) {
     $_SESSION['collection_id_choice'] = $_SESSION['user']['collections'][0];
@@ -17,6 +19,24 @@ if (isset($_REQUEST['resId']) && $_REQUEST['resId'] <> '') {
     $resId = $_SESSION['doc_id'];
 }
 
+//test si le paramètre attach_type existe. Possible de mettre plusieurs types separes par une virgule
+if (isset($_REQUEST['attach_type']) && $_REQUEST['attach_type'] <> ''){
+	$table_type = explode(",", $_REQUEST['attach_type']);
+	$whereAttach = " and (";
+	foreach ($table_type as $value) {
+		$whereAttach .= "attachment_type = '".$value."' or ";
+	}
+	$whereAttach = substr($whereAttach, 0, -4) . ") ";
+}
+if (isset($_REQUEST['attach_type_exclude']) && $_REQUEST['attach_type_exclude'] <> ''){
+	$table_type = explode(",", $_REQUEST['attach_type_exclude']);
+	$whereAttach = " and (";
+	foreach ($table_type as $value) {
+		$whereAttach .= "attachment_type <> '".$value."' and ";
+	}
+	$whereAttach = substr($whereAttach, 0, -4) . ") ";
+}
+
 $viewOnly = false;
 if (isset($_REQUEST['view_only'])) {
     $viewOnly = true;
@@ -27,140 +47,281 @@ require_once 'apps/' . $_SESSION['config']['app_id']
 require_once 'modules/attachments/attachments_tables.php';
 $func = new functions();
 
-$select[RES_ATTACHMENTS_TABLE] = array();
+$db = new dbquery();
+
+//Templates
+$defaultTemplate = 'documents_list_attachments';
+$selectedTemplate = $list->getTemplate();
+if  (empty($selectedTemplate)) {
+    if (!empty($defaultTemplate)) {
+        $list->setTemplate($defaultTemplate);
+        $selectedTemplate = $list->getTemplate();
+    }
+}
+$template_list = array();
+array_push($template_list, 'documents_list_attachments');
+
+$select['res_view_attachments'] = array();
+
+// Important de laisser cet ordre : 'res_id', 'res_id_version', 'relation', 'status'
 array_push(
-    $select[RES_ATTACHMENTS_TABLE], 'res_id', 'typist', 'creation_date', 'title', 'format', 'identifier'
+    $select['res_view_attachments'], 'res_id', 'res_id_version', 'relation', 'status', 'identifier', 'attachment_type', 'title', 'dest_contact_id', 'creation_date', 'typist', 'doc_date', 'updated_by', 'validation_date', 'format'
 );
 
 $where = " res_id_master = " . $resId  . " and coll_id ='"
-       . $_SESSION['collection_id_choice'] . "' and status <> 'DEL'";
-$request = new request;
-$attachArr = $request->select(
-    $select, $where, 'order by res_id desc', $_SESSION['config']['databasetype'], '500'
-);
-//$request->show_array($attachArr);
-
-for ($i = 0; $i < count($attachArr); $i ++) {
-    //$modifyValue = false;
-    for ($j = 0; $j < count($attachArr[$i]); $j ++) {
-        foreach (array_keys($attachArr[$i][$j]) as $value) {
-            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'res_id') {
-                $attachArr[$i][$j]['res_id'] = $attachArr[$i][$j]['value'];
-                $attachArr[$i][$j]['label'] = _ID;
-                $attachArr[$i][$j]['size'] = '18';
-                $attachArr[$i][$j]['label_align'] = 'left';
-                $attachArr[$i][$j]['align'] = 'left';
-                $attachArr[$i][$j]['valign'] = 'bottom';
-                $attachArr[$i][$j]['show'] = false;
-            }
-            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'typist') {
-                $attachArr[$i][$j]['typist'] = $attachArr[$i][$j]['value'];
-                $attachArr[$i][$j]['label'] = _TYPIST;
-                $attachArr[$i][$j]['size'] = '30';
-                $attachArr[$i][$j]['label_align'] = 'left';
-                $attachArr[$i][$j]['align'] = 'left';
-                $attachArr[$i][$j]['valign'] = 'bottom';
-                $attachArr[$i][$j]['show'] = true;
-            }
-            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'title') {
-                $attachArr[$i][$j]['title'] = $attachArr[$i][$j]['value'];
-                $attachArr[$i][$j]['label'] = _TITLE;
-                $attachArr[$i][$j]['size'] = '30';
-                $attachArr[$i][$j]['label_align'] = 'left';
-                $attachArr[$i][$j]['align'] = 'left';
-                $attachArr[$i][$j]['valign'] = 'bottom';
-                $attachArr[$i][$j]['show'] = true;
-            }
-            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'creation_date') {
-                $attachArr[$i][$j]['value'] = $request->format_date_db(
-                    $attachArr[$i][$j]['value'], true
-                );
-                $attachArr[$i][$j]['creation_date'] = $attachArr[$i][$j]['value'];
-                $attachArr[$i][$j]['label'] = _DATE;
-                $attachArr[$i][$j]['size'] = '30';
-                $attachArr[$i][$j]['label_align'] = 'left';
-                $attachArr[$i][$j]['align'] = 'left';
-                $attachArr[$i][$j]['valign'] = 'bottom';
-                $attachArr[$i][$j]['show'] = true;
-            }
-            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'format') {
-                $attachArr[$i][$j]['value'] = $request->show_string(
-                    $attachArr[$i][$j]['value']
-                );
-                $attachArr[$i][$j]['format'] = $attachArr[$i][$j]['value'];
-                $attachArr[$i][$j]['label'] = _FORMAT;
-                $attachArr[$i][$j]['size'] = '5';
-                $attachArr[$i][$j]['label_align'] = 'left';
-                $attachArr[$i][$j]['align'] = 'left';
-                $attachArr[$i][$j]['valign'] = 'bottom';
-                $attachArr[$i][$j]['show'] = true;
-
-                if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j]['value'] == 'maarch') {
-                    //$modifyValue = true;
-                }
-            }
-        }
-    }
-    if (! $viewOnly || ($core->test_service('edit_attachments_from_detail', 'attachments', false))) {
-        $tmp = array(
-            'column' => 'modify_item',
-            'value' => true,
-            'label' => _MODIFY,
-            'size' => '22',
-            'label_align' => 'right',
-            'align' => 'center',
-            'valign' => 'bottom',
-            'show' => false,
-        );
-        array_push($attachArr[$i], $tmp);
-
-        $tmp2 = array(
-            'column' => 'delete_item',
-            'value' => true,
-            'label' => _DELETE,
-            'size' => '22',
-            'label_align' => 'right',
-            'align' => 'center',
-            'valign' => 'bottom',
-            'show' => false,
-        );
-        array_push($attachArr[$i], $tmp2);
+       . $_SESSION['collection_id_choice'] . "' and status <> 'DEL' and status <> 'OBS'";
+	   
+//Filtre sur le type
+if (isset($whereAttach) && $whereAttach <> '') $where .= $whereAttach;
+
+//Order
+    $order = $order_field = '';
+    $order = $list->getOrder();
+    $order_field = $list->getOrderField();
+    if (!empty($order_field) && !empty($order)) 
+        $orderstr = "order by ".$order_field." ".$order;
+    else  {
+        $list->setOrder();
+        $list->setOrderField('creation_date');
+        $orderstr = "order by creation_date desc";
     }
-}
 
-//$request->show_array($attachArr);
-//here we loading the html
-$core->load_html();
-//here we building the header
-$core->load_header('', true, false);
-$mode = 'small';
-if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'normal') {
-    $mode = 'normal';
-}
+$parameters = '';
+//Extra parameters
+if (isset($_REQUEST['size']) && !empty($_REQUEST['size'])) $parameters .= '&size='.$_REQUEST['size'];
+if (isset($_REQUEST['order']) && !empty($_REQUEST['order'])) $parameters .= '&order='.$_REQUEST['order'];
+if (isset($_REQUEST['order_field']) && !empty($_REQUEST['order_field'])) $parameters .= '&order_field='.$_REQUEST['order_field'];
+if (isset($_REQUEST['what']) && !empty($_REQUEST['what'])) $parameters .= '&what='.$_REQUEST['what'];
+if (isset($_REQUEST['start']) && !empty($_REQUEST['start'])) $parameters .= '&start='.$_REQUEST['start'];
 
-?>
-<body style="height:auto;" <?php
-if ($mode == 'small') {
-    echo 'id="iframe"';
-}
-?>>
- <?php
-$listAttach = new list_show();
+//test si le paramètre attach_type existe
+if (isset($_REQUEST['attach_type']) && $_REQUEST['attach_type'] <> '')	$parameters .= "&attach_type=".$_REQUEST['attach_type'];
+if (isset($_REQUEST['attach_type_exclude']) && $_REQUEST['attach_type_exclude'] <> '')	$parameters .= "&attach_type_exclude=".$_REQUEST['attach_type_exclude'];
+if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] <> '') $parameters .= "&fromDetail=".$_REQUEST['fromDetail'];
 
-$usedCss = 'listingsmall';
-if ($mode == 'normal') {
-    $usedCss = 'listing spec detailtabricatordebug';
-}
-$listAttach->list_simple(
-    $attachArr, count($attachArr), '', 'res_id', 'res_id', true,
-    $_SESSION['config']['businessappurl'] . 'index.php?display=true'
-    . '&module=attachments&page=view_attachment', $usedCss,
-    $_SESSION['config']['businessappurl'] . 'index.php?display=true'
-    . '&module=attachments&page=update_attachments&mode=up&collId=' 
-        . $_SESSION['collection_id_choice'], 1024, 768,
-    $_SESSION['config']['businessappurl'] . 'index.php?display=true'
-    . '&module=attachments&page=del_attachment'
-);
-$core->load_js();
-?></body>
-</html>
+if (isset($_REQUEST['load'])) {
+    $core->load_lang();
+    $core->load_html();
+    $core->load_header('', true, false);
+    ?><body><?php
+    $core->load_js();
+
+    //Load list
+    $target = $_SESSION['config']['businessappurl']
+        .'index.php?module=attachments&page=frame_list_attachments'.$parameters;
+    
+    $listContent = $list->loadList($target);
+    echo $listContent;
+
+    ?><div id="container" style="width:100%;min-height:0px;height:0px;"></div></body></html><?php
+} else {
+
+	$request = new request;
+	$attachArr = $request->select(
+	    $select, $where, $orderstr, $_SESSION['config']['databasetype'], '500'
+	);
+	 // $request->show();
+
+	foreach ($attachArr as $key => $value) {
+		if ($attachArr[$key][0]["value"] == "0") {
+			array_shift($attachArr[$key]);
+			$attachArr[$key][0]["column"] = "res_id";
+		} else {
+			unset($attachArr[$key][1]);
+			$attachArr[$key] = array_values($attachArr[$key]);
+		}
+	}
+
+	for ($i = 0; $i < count($attachArr); $i ++) {
+	    //$modifyValue = false;
+	    for ($j = 0; $j < count($attachArr[$i]); $j ++) {
+	        foreach (array_keys($attachArr[$i][$j]) as $value) {
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'res_id') {
+	                $attachArr[$i][$j]['res_id'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _ID;
+	                $attachArr[$i][$j]['size'] = '18';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = false;
+	                $attachArr[$i][$j]['order'] = 'res_id';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'relation') {
+	                $attachArr[$i][$j]['relation'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _VERSION;
+	                $attachArr[$i][$j]['size'] = '18';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'relation';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'identifier') {
+	                $attachArr[$i][$j]['identifier'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _CHRONO_NUMBER;
+	                $attachArr[$i][$j]['size'] = '18';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'identifier';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'attachment_type') {
+	                $attachArr[$i][$j]['value'] = $_SESSION['attachment_types'][$attachArr[$i][$j]['value']];
+	                $attachArr[$i][$j]['attachment_type'] = $_SESSION['attachment_types'][$attachArr[$i][$j]['value']];
+	                $attachArr[$i][$j]['label'] = _ATTACHMENT_TYPES;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'dest_contact_id') {
+	                if ($attachArr[$i][$j]['value'] <> 0 && $attachArr[$i][$j]['value'] <> '' ) {
+	                    $db->query("SELECT firstname, lastname, society FROM contacts_v2 WHERE contact_id =".$attachArr[$i][$j]['value']);
+	                    $res = $db->fetch_object();
+	                    $attachArr[$i][$j]['value'] = $db->protect_string_db($res->firstname) .' '. $db->protect_string_db($res->lastname) . ' '. $db->protect_string_db($res->society);
+	                }
+	                    $attachArr[$i][$j]['dest_contact_id'] = $attachArr[$i][$j]['value'];
+	                    $attachArr[$i][$j]['label'] = _DEST;
+	                    $attachArr[$i][$j]['size'] = '30';
+	                    $attachArr[$i][$j]['label_align'] = 'left';
+	                    $attachArr[$i][$j]['align'] = 'left';
+	                    $attachArr[$i][$j]['valign'] = 'bottom';
+	                    $attachArr[$i][$j]['show'] = true;
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'updated_by') {
+	                $db->query("SELECT lastname FROM users WHERE user_id = '".$attachArr[$i][$j]['value']."'");
+	                $res = $db->fetch_object();
+	                $attachArr[$i][$j]['value'] = $db->protect_string_db($res->lastname);
+	                $attachArr[$i][$j]['updated_by'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _BBY;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'updated_by';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'typist') {
+	                $db->query("SELECT lastname FROM users WHERE user_id = '".$attachArr[$i][$j]['value']."'");
+	                $res = $db->fetch_object();
+	                $attachArr[$i][$j]['typist_id'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['value'] = $db->protect_string_db($res->lastname);
+	                $attachArr[$i][$j]['typist'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _BBY;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'typist';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'title') {
+	                $attachArr[$i][$j]['title'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _OBJECT;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'title';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'creation_date') {
+	                $attachArr[$i][$j]['value'] = $request->format_date_db(
+	                    $attachArr[$i][$j]['value'], true
+	                );
+	                $attachArr[$i][$j]['creation_date'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _CREATED;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'doc_date') {
+	                $attachArr[$i][$j]['value'] = $request->format_date_db(
+	                    $attachArr[$i][$j]['value'], true
+	                );
+	                $attachArr[$i][$j]['doc_date'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _UPDATED_DATE;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'validation_date') {
+	                $attachArr[$i][$j]['value'] = $request->format_date_db(
+	                    $attachArr[$i][$j]['value'], true
+	                );
+	                $attachArr[$i][$j]['validation_date'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _BACK_DATE;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'status') {
+	                $db->query("SELECT label_status FROM status WHERE id = '".$attachArr[$i][$j]['value']."'");
+	                $res = $db->fetch_object();
+	                $attachArr[$i][$j]['value_bis'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['value'] = $db->protect_string_db($res->label_status);
+	                $attachArr[$i][$j]['status'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _STATUS;
+	                $attachArr[$i][$j]['size'] = '30';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = 'status';
+	            }
+	            if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j][$value] == 'format') {
+	                $attachArr[$i][$j]['value'] = $request->show_string(
+	                    $attachArr[$i][$j]['value']
+	                );
+	                $attachArr[$i][$j]['format'] = $attachArr[$i][$j]['value'];
+	                $attachArr[$i][$j]['label'] = _FORMAT;
+	                $attachArr[$i][$j]['size'] = '5';
+	                $attachArr[$i][$j]['label_align'] = 'left';
+	                $attachArr[$i][$j]['align'] = 'left';
+	                $attachArr[$i][$j]['valign'] = 'bottom';
+	                $attachArr[$i][$j]['show'] = true;
+	                $attachArr[$i][$j]['order'] = true;
+	                $attachArr[$i][$j]['order'] = 'format';
+
+	                if (isset($attachArr[$i][$j][$value]) && $attachArr[$i][$j]['value'] == 'maarch') {
+	                    //$modifyValue = true;
+	                }
+	            }
+	        }
+	    }
+		if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] <> ''){
+			array_push($attachArr[$i], array("fromDetail" => $_REQUEST['fromDetail'], "show" => false));
+		}
+	}
+
+    //List
+    $listKey = 'res_id';                                                                    //Clé de la liste
+    $paramsTab = array();                                                               //Initialiser le tableau de paramètres
+    $paramsTab['bool_sortColumn'] = true;                                               //Affichage Tri
+    $paramsTab['pageTitle'] ='';                                                        //Titre de la page
+    $paramsTab['bool_bigPageTitle'] = false;                                            //Affichage du titre en grand
+    $paramsTab['bool_showIconDocument'] =  true;                                        //Affichage de l'icone du document
+    $paramsTab['listHeight'] = '100%';                                                 //Hauteur de la liste
+    $paramsTab['listCss'] = 'listing largerList spec';                                                       //CSS
+    $paramsTab['urlParameters'] =  'display=true'.$parameters;            //Parametres supplémentaires
+    $paramsTab['defaultTemplate'] = $defaultTemplate;                                   //Default template
+    if ($useTemplate && count($template_list) >0 ) {                                    //Templates
+        $paramsTab['templates'] = array();
+        $paramsTab['templates'] = $template_list;
+    }
+    $paramsTab['bool_showTemplateDefaultList'] = true;                                  //Default list (no template)
+    $paramsTab['viewDocumentLink'] = $_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=view_attachment&res_id_master='.$_SESSION['doc_id'];
+
+	$content = $list->showList($attachArr, $paramsTab, $listKey);
+	$status = 0;
+
+	echo "{status : " . $status . ", content : '" . addslashes($debug.$content) . "', error : '" . addslashes($error) . "'}";
+}
\ No newline at end of file
diff --git a/attachments/trunk/js/functions.js b/attachments/trunk/js/functions.js
index 6957d73c268..0c047f27f0a 100644
--- a/attachments/trunk/js/functions.js
+++ b/attachments/trunk/js/functions.js
@@ -40,3 +40,154 @@ function hide_index(mode_hide, display_val)
 		//hide link and show index
 	}
 }
+
+function showAttachmentsForm(path, width, height) {
+    
+    if(typeof(width)==='undefined'){
+        var width = '800';
+    }
+    
+    if(typeof(height)==='undefined'){
+        var height = '480';
+    }  
+    
+    new Ajax.Request(path,
+    {
+        method:'post',
+        parameters: { url : path
+                    },  
+        onSuccess: function(answer) {
+            eval("response = "+answer.responseText);
+           
+            if(response.status == 0){
+             
+                var modal_content = convertToTextVisibleNewLine(response.content);
+                createModal(modal_content, 'form_attachments', height, width); 
+            } else {
+                window.top.$('main_error').innerHTML = response.error;
+            }
+        }
+    });
+}
+
+function ValidAttachmentsForm (path, form_id) {
+
+    new Ajax.Request(path,
+    {
+        asynchronous:false,
+        method:'post',
+        parameters: Form.serialize(form_id),
+        encoding: 'UTF-8',                       
+        onSuccess: function(answer){
+            eval("response = "+answer.responseText);
+            if(response.status == 0){
+                destroyModal('form_attachments'); 
+                eval(response.exec_js);
+            } else {
+                alert(response.error);
+            }
+        }
+    });
+}
+
+function modifyAttachmentsForm(path, width, height) {
+
+    if(typeof(width)==='undefined'){
+        var width = '800';
+    }
+    
+    if(typeof(height)==='undefined'){
+        var height = '480';
+    }  
+
+    new Ajax.Request(path,
+    {
+        method:'post',
+        parameters: { url : path
+                    },  
+        onSuccess: function(answer) {
+            eval("response = "+answer.responseText);
+           
+            if(response.status == 0){
+                var modal_content = convertToTextVisibleNewLine(response.content);
+                createModalinAttachmentList(modal_content, 'form_attachments', height, width); 
+            } else {
+                window.top.$('main_error').innerHTML = response.error;
+            }
+        }
+    });
+}
+
+function setFinalVersion(path) {  
+
+var check = $('final').value;
+
+    new Ajax.Request(path,
+    {
+        asynchronous:false,
+        method:'post',
+        encoding: 'UTF-8',                       
+        onSuccess: function(answer){
+            eval("response = "+answer.responseText);
+            if(response.status == 0 || response.status == 1){
+                eval(response.exec_js);
+            } else {
+                alert(response.error);
+            }
+        }
+    });
+}
+
+function createModalinAttachmentList(txt, id_mod, height, width, mode_frm){
+    if(height == undefined || height=='') {
+        height = '100px';
+    }
+
+    if(width == undefined || width=='') {
+        width = '400px';
+    }
+
+    if( mode_frm == 'fullscreen') {
+        width = (screen.availWidth)+'px';
+        height = (screen.availHeight)+'px';
+    }
+
+    if(id_mod && id_mod!='') {
+        id_layer = id_mod+'_layer';
+    } else {
+        id_mod = 'modal';
+        id_layer = 'lb1-layer';
+    }
+
+    var tmp_width = width;
+    var tmp_height = height;
+    var layer_height = window.top.window.$('container').clientHeight;
+    var layer_width = window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 5;
+    var layer = new Element('div', {'id':id_layer, 'class' : 'lb1-layer', 'style' : "display:block;filter:alpha(opacity=70);opacity:.70;z-index:"+get_z_indexes()['layer']+';width :'+ (layer_width)+"px;height:"+layer_height+'px;'});
+
+    if( mode_frm == 'fullscreen') {
+        var fenetre = new Element('div', {'id' :id_mod,'class' : 'modal', 'style' :'top:0px;left:0px;width:'+width+';height:'+height+";z-index:"+get_z_indexes()['modal']+";position:absolute;" });
+    } else {
+        var fenetre = new Element('div', {'id' :id_mod,'class' : 'modal', 'style' :'top:0px;left:0px;'+'width:'+width+';height:'+height+";z-index:"+get_z_indexes()['modal']+";margin-top:0px;margin-left:0px;position:absolute;" });
+    }
+
+    Element.insert(window.top.window.document.body,layer);
+    Element.insert(window.top.window.document.body,fenetre);
+
+    if( mode_frm == 'fullscreen') {
+        navName = BrowserDetect.browser;
+        if (navName == 'Explorer') {
+            if (width == '1080px') {
+                fenetre.style.width = (window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 55)+"px";
+            }
+        } else {
+            fenetre.style.width = (window.top.window.document.getElementsByTagName('html')[0].offsetWidth - 30)+"px";
+        }
+        fenetre.style.height = (window.top.window.document.getElementsByTagName('body')[0].offsetHeight - 20)+"px";
+    }
+
+    Element.update(fenetre,txt);
+    Event.observe(layer, 'mousewheel', function(event){Event.stop(event);}.bindAsEventListener(), true);
+    Event.observe(layer, 'DOMMouseScroll', function(event){Event.stop(event);}.bindAsEventListener(), false);
+    window.top.window.$(id_mod).focus();
+}
\ No newline at end of file
diff --git a/attachments/trunk/lang/fr.php b/attachments/trunk/lang/fr.php
index 390a460ca51..3a121b42740 100644
--- a/attachments/trunk/lang/fr.php
+++ b/attachments/trunk/lang/fr.php
@@ -62,3 +62,64 @@ if (!defined('_GENERATE_ATTACHMENT_FROM'))
 
 if (!defined('_EDIT_ATTACHMENTS_FROM_DETAILS'))
     define('_EDIT_ATTACHMENTS_FROM_DETAILS', 'G&eacute;rer les pi&egrave;ces jointes depuis la fiche d&eacute;tail');
+
+if (!defined('_CREATED'))
+    define( '_CREATED', 'Cr&eacute;&eacute; le');
+if (!defined('_BBY'))
+    define( '_BBY', 'Par');
+if (!defined('_EXP_DATE'))
+    define( '_EXP_DATE', 'Date de d&eacute;part');
+if (!defined('_CREATE_PJ'))
+    define( '_CREATE_PJ', 'Cr&eacute;er une pi&egrave;ce jointe');
+if (!defined('_ATTACH_FILE'))
+    define( '_ATTACH_FILE', 'Attacher une pi&egrave;ce');
+if (!defined('_MODEL'))
+    define( '_MODEL', 'Mod&egrave;le');
+if (!defined('_CHOOSE_MODEL'))
+    define( '_CHOOSE_MODEL', 'S&eacute;lectionnez le mod&egrave;le');
+if (!defined('_BACK_DATE'))
+    define( '_BACK_DATE', 'Date&nbsp;de&nbsp;retour');
+if (!defined('_ATTACHMENT_TYPES'))
+    define( '_ATTACHMENT_TYPES', 'Type d\'attachement');
+if (!defined('_RESPONSE_PROJECT'))
+    define( '_RESPONSE_PROJECT', 'Projet de r&eacute;ponse');
+if (!defined('_ROUTING'))
+    define( '_ROUTING', 'Fiche de circulation');
+if (!defined('_OUTGOING_MAIL_SIGNED'))
+    define( '_OUTGOING_MAIL_SIGNED', 'Courrier d&eacutepart sign&eacute');
+if (!defined('_A_PJ'))
+    define( '_A_PJ', 'Pi&egrave;ce jointe');
+if (!defined('_CHOOSE_ATTACHMENT_TYPE'))
+    define( '_CHOOSE_ATTACHMENT_TYPE', 'Choisissez un type d\'attachement');
+if (!defined('_UPDATED_DATE'))
+    define( '_UPDATED_DATE', 'Mis&nbsp;&agrave;&nbsp;jour&nbsp;le');
+if (!defined('_FILE_MISSING'))
+    define( '_FILE_MISSING', 'Le fichier est manquant');
+if (!defined('_FILE_EMPTY'))
+    define( '_FILE_EMPTY', 'Le fichier est vide');
+if (!defined('_EDIT_MODEL'))
+    define( '_EDIT_MODEL', 'Editer le mod&egrave;le');
+if (!defined('_ALREADY_MODEL_SELECTED'))
+    define( '_ALREADY_MODEL_SELECTED', 'Mod&egrave;le d&eacute;j&agrave s&eacute;lectionn&eacute;');
+if (!defined('_MODIFY_ANSWER'))
+    define( '_MODIFY_ANSWER', 'Modifier une pi&egrave;ce jointe/un attachement');
+if (!defined('_CREATE_NEW_ATTACHMENT_VERSION'))
+    define( '_CREATE_NEW_ATTACHMENT_VERSION', 'Cr&eacute;er une nouvelle version ?');
+if (!defined('_ATTACH_UPDATED'))
+    define( '_ATTACH_UPDATED', 'Pi&egrave;ce jointe mise &agrave; jour');
+if (!defined('_FINAL_VERSION'))
+    define( '_FINAL_VERSION', 'Version finale');
+if (!defined('_SHOW_PREVIOUS_VERSION'))
+    define( '_SHOW_PREVIOUS_VERSION', 'Voir les versions pr&eacute;c&eacute;dentes');
+if (!defined('_CREATE_ATTACHMENTS_FROM_DETAILS'))
+    define( '_CREATE_ATTACHMENTS_FROM_DETAILS', 'Cr&eacute;er des pi&egrave;ces jointes depuis la fiche d&eacute;tail');
+if (!defined('_DELETE_ATTACHMENTS'))
+    define( '_DELETE_ATTACHMENTS', 'Supprimer les pi&egrave;ces jointes');
+if (!defined('_MODIFY_ATTACHMENTS'))
+    define( '_MODIFY_ATTACHMENTS', 'Modifier les pi&egrave;ces jointes');
+if (!defined('_ALL_ATTACHMENT_TYPES'))
+    define( '_ALL_ATTACHMENT_TYPES', 'Tous les attachements');
+if (!defined('_ATTACHEMENTS'))
+    define( '_ATTACHEMENTS', 'Attachements');
+if (!defined('_WAYBILL'))
+define( '_WAYBILL', 'Bordereau d\'envoi');
\ No newline at end of file
diff --git a/attachments/trunk/previous_attachments.php b/attachments/trunk/previous_attachments.php
new file mode 100644
index 00000000000..7d5ac634add
--- /dev/null
+++ b/attachments/trunk/previous_attachments.php
@@ -0,0 +1,133 @@
+<?php
+
+require_once('core/class/class_core_tools.php');
+require_once "apps".DIRECTORY_SEPARATOR.$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR
+            ."class".DIRECTORY_SEPARATOR."class_users.php";
+$Core_Tools = new core_tools;
+$Core_Tools->load_lang();
+
+$users = new class_users();
+
+$return = '';
+
+if (isset($_REQUEST['res_id_version'])) {
+
+    $status = 0;
+    $return .= '<td colspan="6" style="background-color: #FFF;">';
+        $return .= '<div align="center">';
+            $return .= '<table width="100%" style="background-color: rgba(100, 200, 213, 0.2);">';
+                $return .= '<tr style="font-weight: bold;">';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _STATUS;
+                    $return .= '</th>';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _VERSION;
+                    $return .= '</th>';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _CREATION_DATE;
+                    $return .= '</th>';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _SUBJECT;
+                    $return .= '</th>';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _AUTHOR;
+                    $return .= '</th>';
+                    $return .= '<th style="font-weight: bold; color: black;">';
+                        $return .= _CONSULT;
+                    $return .= '</th>';
+                $return .= '</tr>';
+
+                $db = new dbquery();
+                $db->connect();
+
+                $query = "SELECT attachment_id_master, res_id_master FROM res_view_attachments WHERE res_id_version = "
+                    . $_REQUEST['res_id_version'];
+                $db->query($query);
+				$attach = $db->fetch_object();
+
+                $query = "SELECT status, '1' as relation, creation_date, title, typist, res_id FROM res_attachments WHERE res_id = "
+                    . $attach->attachment_id_master 
+                    . " UNION ALL SELECT status, relation, creation_date, title, typist, res_id_version FROM res_view_attachments WHERE attachment_id_master = "
+                    . $attach->attachment_id_master. " AND status = 'OBS' ORDER BY relation desc";
+                $db->query($query);
+
+                while ($return_db = $db->fetch_object()) {
+                    $return .= '<tr style="border: 1px solid;" style="background-color: #FFF;">';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            $db2 = new dbquery;
+                            $db2->connect();
+                            $query = "SELECT label_status FROM status WHERE id ='".$return_db->status."'";
+                            $db2->query($query);
+                            while ($status_db = $db2->fetch_object()) {
+                                $return .= $status_db->label_status;
+                            }
+                        $return .= '</td>';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            $return .= $return_db->relation;
+                        $return .= '</td>';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            sscanf(substr($return_db->creation_date, 0, 10), "%4s-%2s-%2s", $date_Y, $date_m, $date_d);
+                            switch ($date_m)
+                            {
+                                case '01': $date_m_txt = _JANUARY; break;
+                                case '02': $date_m_txt = _FEBRUARY; break;
+                                case '03': $date_m_txt = _MARCH; break;
+                                case '04': $date_m_txt = _APRIL; break;
+                                case '05': $date_m_txt = _MAY; break;
+                                case '06': $date_m_txt = _JUNE; break;
+                                case '07': $date_m_txt = _JULY; break;
+                                case '08': $date_m_txt = _AUGUST; break;
+                                case '09': $date_m_txt = _SEPTEMBER; break;
+                                case '10': $date_m_txt = _OCTOBER; break;
+                                case '11': $date_m_txt = _NOVEMBER; break;
+                                case '12': $date_m_txt = _DECEMBER; break;
+                                default: $date_m_txt = $date_m;
+                            }
+                            $return .= $date_d.' '.$date_m_txt.' '.$date_Y;
+                        $return .= '</td>';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            $return .= $return_db->title;
+                        $return .= '</td>';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            $current_user = $users->get_user($return_db->typist);
+                            $return .= $current_user['firstname'] . ' ' . $current_user['lastname'];
+                        $return .= '</td>';
+                        $return .= '<td>';
+                            $return .= '&nbsp;&nbsp;';
+                            $return .= '<a ';
+                            $return .= 'href="';
+                              $return .= 'index.php?display=true&module=attachments&page=view_attachment&id='.$return_db->res_id
+                              				.'&res_id_master='.$attach->res_id_master;
+                            $return .= '" ';
+                            $return .= 'target="_blank" ';
+                            $return .= '>';
+                                $return .= '<img ';
+                                $return .= 'src="';
+                                    $return .= 'static.php?filename=picto_dld.gif';
+                                $return .= '" ';
+                                $return .= '/>';
+                            $return .= '</a>';
+                        $return .= '</td>';
+                    $return .= '</tr>';
+                }
+
+            $return .= '</table>';
+            $return .= '<br />';
+        $return .= '</div>';
+    $return .= '</td>';
+} else {
+    $status = 1;
+    $return .= '<td colspan="6" style="background-color: red;">';
+        $return .= '<p style="padding: 10px; color: black;">';
+            $return .= 'Error loading attachments';
+        $return .= '</p>';
+    $return .= '</td>';
+}
+
+echo "{status : " . $status . ", toShow : '" . addslashes($return) . "'}";
+exit ();
diff --git a/attachments/trunk/setFinalVersion.php b/attachments/trunk/setFinalVersion.php
new file mode 100644
index 00000000000..40b0b33acdd
--- /dev/null
+++ b/attachments/trunk/setFinalVersion.php
@@ -0,0 +1,55 @@
+<?php
+
+require_once 'core/class/class_request.php';
+
+$db = new dbquery();
+$db->connect();
+$js = "";
+
+if ((int)$_REQUEST['relation'] > 1) {
+    $column_res = 'res_id_version';
+} else {
+    $column_res = 'res_id';
+}
+
+$db->query("SELECT relation, status 
+                FROM res_view_attachments 
+                WHERE ".$column_res." = ".$_REQUEST['id']." and res_id_master = ".$_SESSION['doc_id']."
+                ORDER BY relation desc");
+
+$res = $db->fetch_object();
+
+if($res->status == 'A_TRA' || $res->status == 'TRA'){
+	if ($res->status == 'A_TRA') {
+		$status = 'TRA';
+	} else {
+		$status = 'A_TRA';		
+	}
+
+	if ($_REQUEST['relation'] == 1) {
+		$table = 'res_attachments';
+	} else {
+		$table = 'res_version_attachments';
+	}
+
+	$db->query("UPDATE ".$table." set status = '".$status."' WHERE res_id = ".$_REQUEST['id']);
+	$status_ajax = 0;
+
+} else {
+	$js .= "alert('Ce courrier a déjà été traité');";
+	$status_ajax = 1;
+}
+
+$js .= 'var eleframe1 =  window.top.document.getElementsByName(\'list_attach\');';
+if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'attachments') {
+	$js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';
+	$js .= '&attach_type_exclude=response_project,outgoing_mail_signed&fromDetail=attachments\';';
+} else if (isset($_REQUEST['fromDetail']) && $_REQUEST['fromDetail'] == 'response'){
+	$js .= 'eleframe1[1].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load';
+	$js .= '&attach_type=response_project,outgoing_mail_signed&fromDetail=response\';';
+} else {
+	$js .= 'eleframe1[0].src = \''.$_SESSION['config']['businessappurl'].'index.php?display=true&module=attachments&page=frame_list_attachments&load\';';
+}
+
+echo "{status: ".$status_ajax.", exec_js : '".addslashes($js)."'}";
+exit;
\ No newline at end of file
diff --git a/attachments/trunk/view_attachment.php b/attachments/trunk/view_attachment.php
index 6854c343d17..f8f608fb3e1 100644
--- a/attachments/trunk/view_attachment.php
+++ b/attachments/trunk/view_attachment.php
@@ -39,8 +39,10 @@ if (! empty($_SESSION['error'])) {
     $db->connect();
 
     $db->query(
-        "select coll_id, res_id_master from " . RES_ATTACHMENTS_TABLE
-        . " where res_id = " . $sId
+        "SELECT coll_id, res_id_master 
+            FROM res_view_attachments 
+            WHERE (res_id = " . $sId . " OR res_id_version = ".$sId.") AND res_id_master = ".$_REQUEST['res_id_master']
+            ." ORDER BY relation desc"
     );
     $res = $db->fetch_object();
     $collId = $res->coll_id;
@@ -56,7 +58,7 @@ if (! empty($_SESSION['error'])) {
 
     $table = $sec->retrieve_table_from_coll($collId);
     $db->query(
-        "select res_id from " . $table . " where res_id = " . $resIdMaster
+        "SELECT res_id FROM " . $table . " WHERE res_id = " . $resIdMaster
     );
     //$db->show();
     if ($db->nb_result() == 0) {
@@ -67,8 +69,10 @@ if (! empty($_SESSION['error'])) {
         exit();
     } else {
         $db->query(
-            "select docserver_id, path, filename, format from "
-            . RES_ATTACHMENTS_TABLE . " where res_id = " . $sId
+            "SELECT docserver_id, path, filename, format 
+                FROM res_view_attachments 
+                WHERE (res_id = " . $sId . " OR res_id_version = ".$sId.") AND res_id_master = ".$_REQUEST['res_id_master']
+                        ." ORDER BY relation desc"
         );
 
         if ($db->nb_result() == 0) {
diff --git a/attachments/trunk/xml/services.xml b/attachments/trunk/xml/services.xml
index 9e445b8e914..933a80c1ab9 100644
--- a/attachments/trunk/xml/services.xml
+++ b/attachments/trunk/xml/services.xml
@@ -56,8 +56,30 @@
   </SERVICE>
    <SERVICE>
    <id>edit_attachments_from_detail</id>
-   <name>_EDIT_ATTACHMENTS_FROM_DETAILS</name>
-   <comment>_EDIT_ATTACHMENTS_FROM_DETAILS</comment>
+   <name>_CREATE_ATTACHMENTS_FROM_DETAILS</name>
+   <comment>_CREATE_ATTACHMENTS_FROM_DETAILS</comment>
+   <servicetype>use</servicetype>
+   <system_service>false</system_service>
+   <enabled>true</enabled>
+   <WHEREAMIUSED>
+        <page>frame_list_attachments.php</page>
+    </WHEREAMIUSED>
+  </SERVICE>
+  <SERVICE>
+   <id>modify_attachments</id>
+   <name>_MODIFY_ATTACHMENTS</name>
+   <comment>_MODIFY_ATTACHMENTS</comment>
+   <servicetype>use</servicetype>
+   <system_service>false</system_service>
+   <enabled>true</enabled>
+   <WHEREAMIUSED>
+        <page>frame_list_attachments.php</page>
+    </WHEREAMIUSED>
+ </SERVICE>
+  <SERVICE>
+   <id>delete_attachments</id>
+   <name>_DELETE_ATTACHMENTS</name>
+   <comment>_DELETE_ATTACHMENTS</comment>
    <servicetype>use</servicetype>
    <system_service>false</system_service>
    <enabled>true</enabled>
-- 
GitLab