From f72faa74944876accbffd249d57fc072aca406ae Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Tue, 23 Jun 2020 15:01:54 +0200
Subject: [PATCH] FEAT #13671 TIME 1:45 Installer fixes

---
 .gitlab-ci.yml                               |  8 +--
 src/core/controllers/CoreController.php      | 17 ++++++
 src/core/controllers/InstallerController.php | 59 +++++++++++++-------
 3 files changed, 61 insertions(+), 23 deletions(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 6d989635380..622a87b4788 100755
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -30,10 +30,10 @@ before_script:
   - bash ci/docker_install_php.sh > /dev/null
   - bash ci/docker_install_database.sh > /dev/null
   - mkdir -p /opt/maarch/docservers/indexes/{letterbox_coll,attachments_coll,version_attachments_coll}
-  - mkdir -p /opt/maarch/docservers/{ai,manual,manual_attachments,templates,acknowledgement_receipts}
-  - mkdir -p /opt/maarch/docservers/{convert_attachments,convert_attachments_version,convert_mlb}
-  - mkdir -p /opt/maarch/docservers/{fulltext_attachments,fulltext_attachments_version,fulltext_mlb}
-  - mkdir -p /opt/maarch/docservers/{thumbnails_attachments,thumbnails_attachments_version,thumbnails_mlb}
+  - mkdir -p /opt/maarch/docservers/{ai,resources,attachments,templates,acknowledgement_receipts}
+  - mkdir -p /opt/maarch/docservers/{convert_attachments,convert_resources}
+  - mkdir -p /opt/maarch/docservers/{fulltext_attachments,fulltext_resources}
+  - mkdir -p /opt/maarch/docservers/{thumbnails_attachments,thumbnails_resources}
   - mkdir -p /var/www/html/
   - ln -s $CI_PROJECT_DIR /var/www/html/MaarchCourrier
   - cd /var/www/html/MaarchCourrier
diff --git a/src/core/controllers/CoreController.php b/src/core/controllers/CoreController.php
index 92560152ced..a67cbb0e15a 100755
--- a/src/core/controllers/CoreController.php
+++ b/src/core/controllers/CoreController.php
@@ -142,4 +142,21 @@ class CoreController
 
         return $maximumSize;
     }
+
+    public static function getErrorReportingFromPhpIni()
+    {
+        $bits = ini_get('error_reporting');
+
+        $errorReporting = [];
+        while ($bits > 0) {
+            $end = 0;
+            for ($i = 0, $n = 0; $i <= $bits; $i = 1 * pow(2, $n), $n++) {
+                $end = $i;
+            }
+            $errorReporting[] = $end;
+            $bits = $bits - $end;
+        }
+
+        return $errorReporting;
+    }
 }
diff --git a/src/core/controllers/InstallerController.php b/src/core/controllers/InstallerController.php
index caa54704ded..c65dc47f96a 100644
--- a/src/core/controllers/InstallerController.php
+++ b/src/core/controllers/InstallerController.php
@@ -32,6 +32,13 @@ class InstallerController
         $output = explode(':', $output[0]);
         $unoconv = !empty($output[1]);
 
+        exec('whereis netcat', $outputNetcat, $returnNetcat);
+        $outputNetcat = explode(':', $outputNetcat[0]);
+
+        exec('whereis nmap', $outputNmap, $returnNmap);
+        $outputNmap = explode(':', $outputNmap[0]);
+        $netcatOrNmap = !empty($outputNetcat[1]) || !empty($outputNmap[1]);
+
         $pdoPgsql = @extension_loaded('pdo_pgsql');
         $pgsql = @extension_loaded('pgsql');
         $mbstring = @extension_loaded('mbstring');
@@ -48,18 +55,14 @@ class InstallerController
         $writable = is_writable('.') && is_readable('.');
 
         $displayErrors = (ini_get('display_errors') == '1');
-        $errorReporting = (ini_get('error_reporting') >= 22519);
-
-        exec('whereis netcat', $outputNetcat, $returnNetcat);
-        $outputNetcat = explode(':', $outputNetcat[0]);
-        exec('whereis nmap', $outputNmap, $returnNmap);
-        $outputNmap = explode(':', $outputNmap[0]);
-        $netcatOrNmap = !empty($outputNetcat[1]) || !empty($outputNmap[1]);
+        $errorReporting = CoreController::getErrorReportingFromPhpIni();
+        $errorReporting = !in_array(8, $errorReporting);
 
         $prerequisites = [
             'phpVersion'        => $phpVersion,
             'phpVersionValid'   => $phpVersionValid,
             'unoconv'           => $unoconv,
+            'netcatOrNmap'      => $netcatOrNmap,
             'pdoPgsql'          => $pdoPgsql,
             'pgsql'             => $pgsql,
             'mbstring'          => $mbstring,
@@ -74,8 +77,7 @@ class InstallerController
             'zip'               => $zip,
             'writable'          => $writable,
             'displayErrors'     => $displayErrors,
-            'errorReporting'    => $errorReporting,
-            'netcatOrNmap'      => $netcatOrNmap
+            'errorReporting'    => $errorReporting
         ];
 
         return $response->withJson(['prerequisites' => $prerequisites]);
@@ -129,6 +131,8 @@ class InstallerController
 
         if (!Validator::stringType()->notEmpty()->validate($body['customId'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body customId is empty or not a string']);
+        } elseif (!preg_match('/^[a-zA-Z0-9_\-]*$/', $body['customId'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Body customId has unauthorized characters']);
         }
 
         if (is_dir("custom/{$body['customId']}")) {
@@ -186,8 +190,12 @@ class InstallerController
             return $response->withStatus(400)->withJson(['errors' => 'Body password is empty or not a string']);
         } elseif (!Validator::stringType()->notEmpty()->validate($body['name'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body name is empty or not a string']);
+        } elseif (!preg_match('/^[a-zA-Z0-9_\-]*$/', $body['name'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Body name has unauthorized characters']);
         } elseif (!Validator::stringType()->notEmpty()->validate($body['customId'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body customId is empty or not a string']);
+        } elseif (!is_file("custom/{$body['customId']}/apps/maarch_entreprise/xml/config.json")) {
+            return $response->withStatus(400)->withJson(['errors' => 'Custom does not exist']);
         }
 
         if (empty($body['alreadyCreated'])) {
@@ -196,14 +204,25 @@ class InstallerController
                 return $response->withStatus(400)->withJson(['errors' => 'Database connection failed']);
             }
 
-            $request = "CREATE DATABASE \"{$body['name']}\" WITH TEMPLATE template0 ENCODING = 'UTF8'";
-            $result = pg_query($request);
+            $result = pg_query("CREATE DATABASE \"{$body['name']}\" WITH TEMPLATE template0 ENCODING = 'UTF8'");
             if (!$result) {
                 return $response->withStatus(400)->withJson(['errors' => 'Database creation failed']);
             }
 
             @pg_query("ALTER DATABASE '{$body['name']}' SET DateStyle =iso, dmy");
             pg_close();
+        } else {
+            $connection = "host={$body['server']} port={$body['port']} user={$body['user']} password={$body['password']} dbname={$body['name']}";
+            if (!@pg_connect($connection)) {
+                return $response->withStatus(400)->withJson(['errors' => 'Database connection failed']);
+            }
+
+            $result = pg_query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'");
+            $row = pg_fetch_row($result);
+            if (!empty($row)) {
+                return $response->withStatus(400)->withJson(['errors' => 'Given database has tables']);
+            }
+            pg_close();
         }
 
         $options = [
@@ -215,20 +234,20 @@ class InstallerController
         $dsn = "pgsql:host={$body['server']};port={$body['port']};dbname={$body['name']}";
         $db = new \PDO($dsn, $body['user'], $body['password'], $options);
 
-        $fileContent = @file_get_contents('sql/structure.sql');
-        if (!$fileContent) {
-            return $response->withStatus(400)->withJson(['errors' => 'Cannot read structure.sql']);
+        if (!is_file('sql/structure.sql')) {
+            return $response->withStatus(400)->withJson(['errors' => 'File sql/structure.sql does not exist']);
         }
+        $fileContent = file_get_contents('sql/structure.sql');
         $result = $db->exec($fileContent);
         if ($result === false) {
             return $response->withStatus(400)->withJson(['errors' => 'Request failed : run structure.sql']);
         }
 
         if (!empty($body['data'])) {
-            $fileContent = @file_get_contents("sql/{$body['data']}.sql");
-            if (!$fileContent) {
-                return $response->withStatus(400)->withJson(['errors' => "Cannot read {$body['data']}.sql"]);
+            if (!is_file("sql/{$body['data']}.sql")) {
+                return $response->withStatus(400)->withJson(['errors' => "File sql/{$body['data']}.sql does not exist"]);
             }
+            $fileContent = @file_get_contents("sql/{$body['data']}.sql");
             $result = $db->exec($fileContent);
             if ($result ===  false) {
                 return $response->withStatus(400)->withJson(['errors' => "Request failed : run {$body['data']}.sql"]);
@@ -260,12 +279,14 @@ class InstallerController
 
         if (!Validator::stringType()->notEmpty()->validate($body['path'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body path is empty or not a string']);
-        } elseif (!Validator::stringType()->notEmpty()->validate($body['customId'])) {
-            return $response->withStatus(400)->withJson(['errors' => 'Body customId is empty or not a string']);
         } elseif (!is_dir($body['path'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body path does not exist']);
         } elseif (!is_writable($body['path'])) {
             return $response->withStatus(400)->withJson(['errors' => 'Body path is not writable']);
+        } elseif (!Validator::stringType()->notEmpty()->validate($body['customId'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Body customId is empty or not a string']);
+        } elseif (!is_file("custom/{$body['customId']}/apps/maarch_entreprise/xml/config.json")) {
+            return $response->withStatus(400)->withJson(['errors' => 'Custom does not exist']);
         }
 
         $body['path'] = rtrim($body['path'], '/');
-- 
GitLab