From 6dbc0c33b8d2ba1515e09847be22a0ac6df86c2b Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Tue, 22 Oct 2019 15:42:01 +0200
Subject: [PATCH] FIX #12070 TIME 0:50 File is not mandatory

---
 migration/19.12/1912.sql                      | 39 +++++++------
 .../resource/controllers/ResController.php    | 54 +++++++++++-------
 .../resource/controllers/StoreController.php  | 56 ++++++++++---------
 src/app/resource/models/ResModelAbstract.php  |  6 +-
 4 files changed, 90 insertions(+), 65 deletions(-)

diff --git a/migration/19.12/1912.sql b/migration/19.12/1912.sql
index 293ecd26e58..ca77af1327e 100644
--- a/migration/19.12/1912.sql
+++ b/migration/19.12/1912.sql
@@ -232,22 +232,6 @@ DO $$ BEGIN
 END$$;
 
 
-/* RES_LETTERBOX */
-ALTER TABLE res_letterbox DROP COLUMN IF EXISTS model_id;
-ALTER TABLE res_letterbox ADD COLUMN model_id INTEGER;
-DO $$ BEGIN
-    IF (SELECT count(column_name) from information_schema.columns where table_name = 'res_letterbox' and column_name = 'typist' and data_type != 'integer') THEN
-        ALTER TABLE res_letterbox ADD COLUMN typist_tmp integer;
-        UPDATE res_letterbox set typist_tmp = (select id FROM users where users.user_id = res_letterbox.typist);
-        UPDATE res_letterbox set typist_tmp = 0 WHERE typist_tmp IS NULL;
-        ALTER TABLE res_letterbox ALTER COLUMN typist_tmp set not null;
-        ALTER TABLE res_letterbox DROP COLUMN IF EXISTS typist;
-        ALTER TABLE res_letterbox RENAME COLUMN typist_tmp TO typist;
-        UPDATE baskets SET basket_clause = REGEXP_REPLACE(basket_clause, 'typist(\s*)=(\s*)@user', 'typist = @user_id', 'gmi');
-        UPDATE security SET where_clause = REGEXP_REPLACE(where_clause, 'typist(\s*)=(\s*)@user', 'typist = @user_id', 'gmi');
-    END IF;
-END$$;
-
 /* MLB COLL EXT */
 DO $$ BEGIN
     IF (SELECT count(attname) FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'res_letterbox') AND attname = 'category_id') = 0 THEN
@@ -301,6 +285,28 @@ DO $$ BEGIN
 END$$;
 
 
+/* RES_LETTERBOX */
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS model_id;
+ALTER TABLE res_letterbox ADD COLUMN model_id INTEGER;
+UPDATE res_letterbox set model_id = 2 WHERE category_id = 'outgoing';
+UPDATE res_letterbox set model_id = 3 WHERE category_id = 'internal';
+UPDATE res_letterbox set model_id = 4 WHERE category_id = 'ged_doc';
+UPDATE res_letterbox set model_id = 1 WHERE model_id IS NULL;
+ALTER TABLE res_letterbox ALTER COLUMN model_id set not null;
+DO $$ BEGIN
+    IF (SELECT count(column_name) from information_schema.columns where table_name = 'res_letterbox' and column_name = 'typist' and data_type != 'integer') THEN
+        ALTER TABLE res_letterbox ADD COLUMN typist_tmp integer;
+        UPDATE res_letterbox set typist_tmp = (select id FROM users where users.user_id = res_letterbox.typist);
+        UPDATE res_letterbox set typist_tmp = 0 WHERE typist_tmp IS NULL;
+        ALTER TABLE res_letterbox ALTER COLUMN typist_tmp set not null;
+        ALTER TABLE res_letterbox DROP COLUMN IF EXISTS typist;
+        ALTER TABLE res_letterbox RENAME COLUMN typist_tmp TO typist;
+        UPDATE baskets SET basket_clause = REGEXP_REPLACE(basket_clause, 'typist(\s*)=(\s*)@user', 'typist = @user_id', 'gmi');
+        UPDATE security SET where_clause = REGEXP_REPLACE(where_clause, 'typist(\s*)=(\s*)@user', 'typist = @user_id', 'gmi');
+    END IF;
+END$$;
+
+
 /* REFACTORING DATA */
 DO $$ BEGIN
   IF (SELECT count(attname) FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'usergroups') AND attname = 'enabled') THEN
@@ -369,6 +375,7 @@ ALTER TABLE tags ALTER COLUMN label TYPE character varying(128);
 UPDATE priorities SET delays = 30 WHERE delays IS NULL;
 ALTER TABLE priorities ALTER COLUMN delays SET NOT NULL;
 ALTER TABLE res_letterbox ALTER COLUMN status DROP NOT NULL;
+ALTER TABLE res_letterbox ALTER COLUMN docserver_id DROP NOT NULL;
 
 /* REFACTORING SUPPRESSION */
 DO $$ BEGIN
diff --git a/src/app/resource/controllers/ResController.php b/src/app/resource/controllers/ResController.php
index b2f2f798c84..b79653dfd6c 100755
--- a/src/app/resource/controllers/ResController.php
+++ b/src/app/resource/controllers/ResController.php
@@ -82,15 +82,17 @@ class ResController
 
         ResController::createAdjacentData(['body' => $body, 'resId' => $resId]);
 
-        ConvertPdfController::convert([
-            'resId'     => $resId,
-            'collId'    => 'letterbox_coll',
-            'isVersion' => false
-        ]);
+        if (!empty($body['encodedFile'])) {
+            ConvertPdfController::convert([
+                'resId'     => $resId,
+                'collId'    => 'letterbox_coll',
+                'isVersion' => false
+            ]);
 
-        $customId = CoreConfigModel::getCustomId();
-        $customId = empty($customId) ? 'null' : $customId;
-        exec("php src/app/convert/scripts/FullTextScript.php --customId {$customId} --resId {$resId} --collId 'letterbox_coll' --userId {$GLOBALS['id']} > /dev/null &");
+            $customId = CoreConfigModel::getCustomId();
+            $customId = empty($customId) ? 'null' : $customId;
+            exec("php src/app/convert/scripts/FullTextScript.php --customId {$customId} --resId {$resId} --collId 'letterbox_coll' --userId {$GLOBALS['id']} > /dev/null &");
+        }
 
         HistoryController::add([
             'tableName' => 'res_letterbox',
@@ -165,6 +167,10 @@ class ResController
             return $response->withStatus(400)->withJson(['errors' => 'Document does not exist']);
         }
 
+        if (empty($document['filename'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Document has no file']);
+        }
+
         if ($document['category_id'] == 'outgoing') {
             $attachment = AttachmentModel::getOnView([
                 'select'    => ['res_id', 'res_id_version', 'docserver_id', 'path', 'filename'],
@@ -328,6 +334,10 @@ class ResController
             return $response->withStatus(400)->withJson(['errors' => 'Document does not exist']);
         }
 
+        if (empty($document['filename'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Document has no file']);
+        }
+
         if ($document['category_id'] == 'outgoing') {
             $attachment = AttachmentModel::getOnView([
                 'select'    => ['res_id', 'res_id_version', 'docserver_id', 'path', 'filename', 'fingerprint'],
@@ -397,7 +407,13 @@ class ResController
         }
 
         $pathToThumbnail = 'apps/maarch_entreprise/img/noThumbnail.png';
-        if (ResController::hasRightByResId(['resId' => [$aArgs['resId']], 'userId' => $GLOBALS['id']])) {
+
+        $document = ResModel::getById(['select' => ['filename'], 'resId' => $aArgs['resId']]);
+        if (empty($document)) {
+            return $response->withStatus(400)->withJson(['errors' => 'Document does not exist']);
+        }
+
+        if (!empty($document['filename']) && ResController::hasRightByResId(['resId' => [$aArgs['resId']], 'userId' => $GLOBALS['id']])) {
             $tnlAdr = AdrModel::getTypedDocumentAdrByResId([
                 'select'    => ['docserver_id', 'path', 'filename'],
                 'resId'     => $aArgs['resId'],
@@ -795,17 +811,17 @@ class ResController
     {
         $body = $args['body'];
 
-        if (!Validator::notEmpty()->validate($body['encodedFile'])) {
-            return ['errors' => 'Body encodedFile is empty'];
-        } elseif (!Validator::stringType()->notEmpty()->validate($body['format'])) {
-            return ['errors' => 'Body format is empty or not a string'];
-        }
+        if (!empty($body['encodedFile'])) {
+            if (!Validator::stringType()->notEmpty()->validate($body['format'])) {
+                return ['errors' => 'Body format is empty or not a string'];
+            }
 
-        $file     = base64_decode($body['encodedFile']);
-        $finfo    = new \finfo(FILEINFO_MIME_TYPE);
-        $mimeType = $finfo->buffer($file);
-        if (!StoreController::isFileAllowed(['extension' => $body['format'], 'type' => $mimeType])) {
-            return ['errors' => "Format with this mimeType is not allowed : {$body['format']} {$mimeType}"];
+            $file     = base64_decode($body['encodedFile']);
+            $finfo    = new \finfo(FILEINFO_MIME_TYPE);
+            $mimeType = $finfo->buffer($file);
+            if (!StoreController::isFileAllowed(['extension' => $body['format'], 'type' => $mimeType])) {
+                return ['errors' => "Format with this mimeType is not allowed : {$body['format']} {$mimeType}"];
+            }
         }
 
         return true;
diff --git a/src/app/resource/controllers/StoreController.php b/src/app/resource/controllers/StoreController.php
index 47bbc09502b..9ee5ef1087f 100755
--- a/src/app/resource/controllers/StoreController.php
+++ b/src/app/resource/controllers/StoreController.php
@@ -33,28 +33,30 @@ class StoreController
         ValidatorModel::intVal($args, ['doctype', 'modelId']);
 
         try {
-            $fileContent = base64_decode(str_replace(['-', '_'], ['+', '/'], $args['encodedFile']));
+            $resId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'res_id_mlb_seq']);
 
-            $storeResult = DocserverController::storeResourceOnDocServer([
-                'collId'            => 'letterbox_coll',
-                'docserverTypeId'   => 'DOC',
-                'encodedResource'   => base64_encode($fileContent),
-                'format'            => $args['format']
-            ]);
-            if (!empty($storeResult['errors'])) {
-                return ['errors' => '[storeResource] ' . $storeResult['errors']];
-            }
+            $data = ['resId' => $resId];
 
-            $resId = DatabaseModel::getNextSequenceValue(['sequenceId' => 'res_id_mlb_seq']);
+            if (!empty($args['encodedFile'])) {
+                $fileContent = base64_decode(str_replace(['-', '_'], ['+', '/'], $args['encodedFile']));
+
+                $storeResult = DocserverController::storeResourceOnDocServer([
+                    'collId'            => 'letterbox_coll',
+                    'docserverTypeId'   => 'DOC',
+                    'encodedResource'   => base64_encode($fileContent),
+                    'format'            => $args['format']
+                ]);
+                if (!empty($storeResult['errors'])) {
+                    return ['errors' => '[storeResource] ' . $storeResult['errors']];
+                }
+
+                $data['docserver_id'] = $storeResult['docserver_id'];
+                $data['filename'] = $storeResult['file_destination_name'];
+                $data['filesize'] = $storeResult['fileSize'];
+                $data['path'] = $storeResult['directory'];
+                $data['fingerprint'] = $storeResult['fingerPrint'];
+            }
 
-            $data = [
-                'resId'         => $resId,
-                'docserver_id'  => $storeResult['docserver_id'],
-                'filename'      => $storeResult['file_destination_name'],
-                'filesize'      => $storeResult['fileSize'],
-                'path'          => $storeResult['directory'],
-                'fingerprint'   => $storeResult['fingerPrint']
-            ];
             $data = array_merge($args, $data);
             $data = StoreController::prepareStorage($data);
 
@@ -109,9 +111,9 @@ class StoreController
 
     public static function prepareStorage(array $args)
     {
-        ValidatorModel::notEmpty($args, ['docserver_id', 'filename', 'format', 'filesize', 'path', 'fingerprint', 'resId', 'modelId']);
+        ValidatorModel::notEmpty($args, ['resId', 'modelId']);
         ValidatorModel::stringType($args, ['docserver_id', 'filename', 'format', 'path', 'fingerprint']);
-        ValidatorModel::intVal($args, ['filesize', 'resId', 'modelId']);
+        ValidatorModel::intVal($args, ['resId', 'modelId', 'filesize']);
 
         $indexingModel = IndexingModelModel::getById(['id' => $args['modelId'], 'select' => ['category']]);
 
@@ -140,7 +142,6 @@ class StoreController
             'type_id'               => $args['doctype'],
             'subject'               => $args['subject'] ?? null,
             'alt_identifier'        => $chrono,
-            'format'                => $args['format'],
             'typist'                => $args['typist'],
             'status'                => $args['status'] ?? null,
             'destination'           => $args['destination'] ?? null,
@@ -154,11 +155,12 @@ class StoreController
             'barcode'               => $args['barcode'] ?? null,
             'origin'                => $args['origin'] ?? null,
             'external_id'           => $externalId,
-            'docserver_id'          => $args['docserver_id'],
-            'filename'              => $args['filename'],
-            'filesize'              => $args['filesize'],
-            'path'                  => $args['path'],
-            'fingerprint'           => $args['fingerprint'],
+            'format'                => empty($args['encodedFile']) ? null : $args['format'],
+            'docserver_id'          => empty($args['encodedFile']) ? null : $args['docserver_id'],
+            'filename'              => empty($args['encodedFile']) ? null : $args['filename'],
+            'filesize'              => empty($args['encodedFile']) ? null : $args['filesize'],
+            'path'                  => empty($args['encodedFile']) ? null : $args['path'],
+            'fingerprint'           => empty($args['encodedFile']) ? null : $args['fingerprint'],
             'creation_date'         => 'CURRENT_TIMESTAMP'
         ];
 
diff --git a/src/app/resource/models/ResModelAbstract.php b/src/app/resource/models/ResModelAbstract.php
index 63d1d61360b..8ca9e91587b 100755
--- a/src/app/resource/models/ResModelAbstract.php
+++ b/src/app/resource/models/ResModelAbstract.php
@@ -81,9 +81,9 @@ abstract class ResModelAbstract
 
     public static function create(array $args)
     {
-        ValidatorModel::notEmpty($args, ['res_id', 'format', 'typist', 'creation_date', 'docserver_id', 'path', 'filename', 'fingerprint', 'filesize', 'category_id']);
-        ValidatorModel::stringType($args, ['format', 'creation_date', 'docserver_id', 'path', 'filename', 'fingerprint', 'category_id']);
-        ValidatorModel::intVal($args, ['filesize', 'res_id', 'typist']);
+        ValidatorModel::notEmpty($args, ['res_id', 'model_id', 'category_id', 'typist', 'creation_date']);
+        ValidatorModel::stringType($args, ['category_id', 'creation_date', 'format', 'docserver_id', 'path', 'filename', 'fingerprint', ]);
+        ValidatorModel::intVal($args, ['res_id', 'model_id', 'typist', 'filesize']);
 
         DatabaseModel::insert([
             'table'         => 'res_letterbox',
-- 
GitLab