From 7de00818381141a959982b5c5f8aa835f3f94476 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Thu, 3 Dec 2020 17:25:43 +0100
Subject: [PATCH] FEAT #14996 TIME 0:20 Send all integrated attachments to
 ixBus

---
 .../controllers/IxbusController.php           | 87 ++++++++++++++-----
 1 file changed, 63 insertions(+), 24 deletions(-)

diff --git a/src/app/external/externalSignatoryBook/controllers/IxbusController.php b/src/app/external/externalSignatoryBook/controllers/IxbusController.php
index d08fde2b0ff..a95236d7a28 100755
--- a/src/app/external/externalSignatoryBook/controllers/IxbusController.php
+++ b/src/app/external/externalSignatoryBook/controllers/IxbusController.php
@@ -188,11 +188,24 @@ class IxbusController
         }
         $userInfo  = IxbusController::getInfoUtilisateur(['config' => $aArgs['config'], 'login' => $aArgs['loginIxbus'], 'password' => $aArgs['passwordIxbus']]);
 
+        $annexes = [];
+        $annexes['letterbox'] = ResModel::get([
+            'select' => ['res_id', 'path', 'filename', 'docserver_id', 'format', 'category_id', 'external_id', 'integrations'],
+            'where'  => ['res_id = ?'],
+            'data'   => [$aArgs['resIdMaster']]
+        ]);
+
+        if (!empty($annexes['letterbox'][0]['docserver_id'])) {
+            $adrMainInfo = ConvertPdfController::getConvertedPdfById(['resId' => $aArgs['resIdMaster'], 'collId' => 'letterbox_coll']);
+            $letterboxPath = DocserverModel::getByDocserverId(['docserverId' => $adrMainInfo['docserver_id'], 'select' => ['path_template']]);
+            $annexes['letterbox'][0]['filePath'] = $letterboxPath['path_template'] . str_replace('#', '/', $adrMainInfo['path']) . $adrMainInfo['filename'];
+        }
+
         $attachments = AttachmentModel::get([
             'select'    => [
                 'res_id', 'title', 'identifier', 'attachment_type',
                 'status', 'typist', 'docserver_id', 'path', 'filename', 'creation_date',
-                'validation_date', 'relation', 'origin_id'
+                'validation_date', 'relation', 'origin_id', 'fingerprint'
             ],
             'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP', 'SEND_MASS')", "in_signature_book = 'true'"],
             'data'      => [$aArgs['resIdMaster'], ['incoming_mail_attachment', 'signed_response']]
@@ -202,7 +215,17 @@ class IxbusController
         $attachmentTypes = array_column($attachmentTypes, 'signable', 'type_id');
         foreach ($attachments as $key => $value) {
             if (!$attachmentTypes[$value['attachment_type']]) {
+                $annexeAttachmentPath = DocserverModel::getByDocserverId(['docserverId' => $value['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
+                $value['filePath']    = $annexeAttachmentPath['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $value['path']) . $value['filename'];
+
+                $docserverType = DocserverTypeModel::getById(['id' => $annexeAttachmentPath['docserver_type_id'], 'select' => ['fingerprint_mode']]);
+                $fingerprint = StoreController::getFingerPrint(['filePath' => $value['filePath'], 'mode' => $docserverType['fingerprint_mode']]);
+                if ($value['fingerprint'] != $fingerprint) {
+                    return ['error' => 'Fingerprints do not match'];
+                }
+
                 unset($attachments[$key]);
+                $annexes['attachments'][] = $value;
             }
         }
 
@@ -235,13 +258,16 @@ class IxbusController
                 return ['error' => 'Fingerprints do not match'];
             }
 
-            $encodedZipFile = IxbusController::createZip(['filepath' => $filePath, 'filename' => $adrInfo['filename'], 'res_id_master' => $aArgs['resIdMaster']]);
+            $encodedZipFile = IxbusController::createZip(['resId' => $resId, 'filename' => $adrInfo['filename'], 'resIdMaster' => $aArgs['resIdMaster'], 'collId' => $collId, 'annexes' => $annexes]);
+            if (!empty($encodedZipFile['error'])) {
+                return ['error' => $encodedZipFile['error']];
+            }
 
             $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
             <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
               <soap:Body>
                 <SendDossier xmlns="http://www.srci.fr">
-                  <ContenuDocumentZip>'. $encodedZipFile .'</ContenuDocumentZip>
+                  <ContenuDocumentZip>'. $encodedZipFile['encodedFile'] .'</ContenuDocumentZip>
                   <NomDocumentPrincipal>'. $adrInfo['filename'] . '</NomDocumentPrincipal>
                   <NomDossier>'. $value['title'] .'</NomDossier>
                   <NomModele>'. $aArgs['messageModel'] .'</NomModele>
@@ -284,13 +310,17 @@ class IxbusController
                 return ['error' => 'Fingerprints do not match'];
             }
 
-            $encodedZipFile = IxbusController::createZip(['filepath' => $filePath, 'filename' => $adrInfo['filename'], 'res_id_master' => $resId]);
+            unset($annexes['letterbox']);
+            $encodedZipFile = IxbusController::createZip(['resId' => $resId, 'filename' => $adrInfo['filename'], 'resIdMaster' => $resId, 'collId' => $collId, 'annexes' => $annexes]);
+            if (!empty($encodedZipFile['error'])) {
+                return ['error' => $encodedZipFile['error']];
+            }
 
             $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
             <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
               <soap:Body>
                 <SendDossier xmlns="http://www.srci.fr">
-                  <ContenuDocumentZip>'. $encodedZipFile .'</ContenuDocumentZip>
+                  <ContenuDocumentZip>'. $encodedZipFile['encodedFile'] .'</ContenuDocumentZip>
                   <NomDocumentPrincipal>'. $adrInfo['filename'] . '</NomDocumentPrincipal>
                   <NomDossier>'. $mainResource['subject'] .'</NomDossier>
                   <NomModele>'. $aArgs['messageModel'] .'</NomModele>
@@ -321,30 +351,39 @@ class IxbusController
 
     public static function createZip($aArgs)
     {
-        $zip = new \ZipArchive();
+        $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $aArgs['resId'], 'collId' => $aArgs['collId']]);
+        if (empty($adrInfo['docserver_id']) || strtolower(pathinfo($adrInfo['filename'], PATHINFO_EXTENSION)) != 'pdf') {
+            return ['error' => 'Document ' . $aArgs['resIdMaster'] . ' is not converted in pdf'];
+        }
+        $attachmentPath     =  DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id'], 'select' => ['path_template']]);
+        $attachmentFilePath = $attachmentPath['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
 
-        $pathInfo    = pathinfo($aArgs['filepath'], PATHINFO_FILENAME);
+        $zip         = new \ZipArchive();
         $tmpPath     = CoreConfigModel::getTmpPath();
-        $zipFilename = $tmpPath . $pathInfo."_".rand().".zip";
-
-        if ($zip->open($zipFilename, \ZipArchive::CREATE) === true) {
-            $zip->addFile($aArgs['filepath'], $aArgs['filename']);
-            
-            $adrInfo             = ConvertPdfController::getConvertedPdfById(['resId' => $aArgs['res_id_master'], 'collId' => 'letterbox_coll']);
-            if (!empty($adrInfo['docserver_id'])) {
-                $docserverInfo       = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
-                $arrivedMailfilePath = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
-                $zip->addFile($arrivedMailfilePath, 'courrier_arrivee.pdf');
-            }
+        $zipFilePath = $tmpPath . 'projet_courrier_' . $aArgs['resIdMaster'] . '_' . rand(0001, 9999) . '_' . rand(0001, 9999) . '.zip';
 
-            $zip->close();
+        if ($zip->open($zipFilePath, \ZipArchive::CREATE)!==true) {
+            return ['error' => "Can not open file : <$zipFilePath>\n"];
+        }
+        $zip->addFile($attachmentFilePath, $aArgs['filename']);
 
-            $fileContent = file_get_contents($zipFilename);
-            $base64 =  base64_encode($fileContent);
-            return $base64;
-        } else {
-            echo 'Impossible de créer l\'archive;';
+        if (!empty($aArgs['annexes']['letterbox'][0]['filePath'])) {
+            $zip->addFile($aArgs['annexes']['letterbox'][0]['filePath'], 'document_principal.' . $aArgs['annexes']['letterbox'][0]['format']);
         }
+
+        if (isset($aArgs['annexes']['attachments'])) {
+            for ($j = 0; $j < count($aArgs['annexes']['attachments']); $j++) {
+                $zip->addFile(
+                    $aArgs['annexes']['attachments'][$j]['filePath'],
+                    'PJ_' . ($j + 1) . '.' . $aArgs['annexes']['attachments'][$j]['format']
+                );
+            }
+        }
+
+        $zip->close();
+        $b64Attachment = base64_encode(file_get_contents($zipFilePath));
+
+        return ['encodedFile' => $b64Attachment];
     }
 
     public static function retrieveSignedMails($aArgs)
-- 
GitLab