Browse Source

ot-admin: various fixes

Olivier Massot 5 years ago
parent
commit
0bf61611a5
1 changed files with 151 additions and 73 deletions
  1. 151 73
      ot_admin/Classes/Controller/SiteController.php

+ 151 - 73
ot_admin/Classes/Controller/SiteController.php

@@ -33,7 +33,6 @@ class SiteController extends ActionController
     const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
     const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
     const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
-    const TEMPLATE_E404 = "OpenTalent.OtTemplating->e404";
 
     // Pages dokType values
     const DOK_PAGE = 1;
@@ -110,10 +109,18 @@ class SiteController extends ActionController
 
         $organization = $this->fetchOrganization($organizationId);
 
+        // This extra-data can not be retrieved from the API for now, but
+        // this shall be set up as soon as possible, to avoid requesting
+        // the prod-back DB directly.
+        $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
+
+        $isNetwork = $organizationExtraData['category'] == 'NETWORK';
+
         // ** Test the existence of a website with this name and or organization id
 
         // Is there a site with this organization's name?
         $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
+        $queryBuilder->getRestrictions()->removeAll();
         $queryBuilder
             ->select('uid')
             ->from('pages')
@@ -122,11 +129,12 @@ class SiteController extends ActionController
         $statement = $queryBuilder->execute();
 
         if ($statement->rowCount() > 0) {
-            throw new \RuntimeException('A website with this name already exists: ' . $organization->getName());
+            throw new \RuntimeException('A website with this name already exists: ' . $organization->getName() . "\n(if you can't see it, it might have been soft-deleted)");
         }
 
         // Is there a site with this organization's id?
         $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
+        $queryBuilder->getRestrictions()->removeAll();
         $statement = $queryBuilder
             ->select('uid')
             ->from('pages')
@@ -134,7 +142,7 @@ class SiteController extends ActionController
             ->andWhere('is_siteroot=1')
             ->execute();
         if ($statement->rowCount() > 0) {
-            throw new \RuntimeException("A website with this organization's id already exists: " . $organization->getName());
+            throw new \RuntimeException("A website with this organization's id already exists: " . $organization->getName() . "\n(if you can't see it, it might have been soft-deleted)");
         }
 
         // ** Create the new website
@@ -197,6 +205,17 @@ class SiteController extends ActionController
                 self::TEMPLATE_MEMBERSCA
             );
 
+            if ($isNetwork) {
+                // > 'Présentation > Les sociétés adhérentes' page
+                $this->insertPage(
+                    $organization,
+                    $this->createdPagesIndex['/presentation'],
+                    'Les sociétés adhérentes',
+                    '/societes-adherentes',
+                    self::TEMPLATE_STRUCTURES
+                );
+            }
+
             // > 'Présentation > Historique' page (hidden by default)
             $this->insertPage(
                 $organization,
@@ -207,13 +226,16 @@ class SiteController extends ActionController
                 ['hidden' => 1]
             );
 
+            // ~ Contact shortcut will be created after the contact page
+
             // > 'Actualités' page (hidden by default)
             $this->insertPage(
                 $organization,
                 $rootUid,
                 'Actualités',
                 '/actualites',
-                self::TEMPLATE_NEWS
+                self::TEMPLATE_NEWS,
+                ['hidden' => 1]
             );
 
             // > 'Saison en cours' page
@@ -233,6 +255,17 @@ class SiteController extends ActionController
                 self::TEMPLATE_EVENTS
             );
 
+            if ($isNetwork) {
+                // > 'Présentation > Les sociétés adhérentes' page
+                $this->insertPage(
+                    $organization,
+                    $this->createdPagesIndex['/presentation'],
+                    'Évènements des structures',
+                    '/evenements-des-structures',
+                    self::TEMPLATE_STRUCTURESEVENTS
+                );
+            }
+
             // > 'Vie interne' page (restricted, hidden by default)
             $this->insertPage(
                 $organization,
@@ -284,13 +317,26 @@ class SiteController extends ActionController
                 '/mentions-legales'
             );
 
+            // > 'Présentation > Contact' shortcut
+            $this->insertPage(
+                $organization,
+                $this->createdPagesIndex['/presentation'],
+                'Contact',
+                '/ecrivez-nous',
+                '',
+                [
+                    'dokType' => self::DOK_SHORTCUT,
+                    'shortcut' => $this->createdPagesIndex['/contact']
+                ]
+            );
+
             // > 'Page introuvable' page (not in the menu, read-only)
             $this->insertPage(
                 $organization,
                 $rootUid,
                 'Page introuvable',
                 '/page-introuvable',
-                self::TEMPLATE_E404,
+                '',
                 [
                     'nav_hide' => 1,
                     'no_search' => 1
@@ -348,7 +394,15 @@ class SiteController extends ActionController
                 ->execute();
 
             // update sys_template
-            $constants = $this->genTemplateConstants($organizationId);
+            $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
+
+            $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
+            $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
+            $include .= ",EXT:form/Configuration/TypoScript/";
+            $include .= ",EXT:news/Configuration/TypoScript";
+            $include .= ",EXT:frontend_editing/Configuration/TypoScript";
+            $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
+            $include .= ",EXT:ot_templating/Configuration/TypoScript";
 
             $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
             $queryBuilder->insert('sys_template')
@@ -359,7 +413,7 @@ class SiteController extends ActionController
                     'root' => 1,
                     'clear' => 3,
                     'config' => "config = 'config.frontend_editing = 1",
-                    'include_static_file' => 'EXT:fluid_styled_content/Configuration/TypoScript/,EXT:fluid_styled_content/Configuration/TypoScript/Styling/,EXT:form/Configuration/TypoScript/,EXT:news/Configuration/TypoScript,EXT:frontend_editing/Configuration/TypoScript,EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9,EXT:ot_templating/Configuration/TypoScript',
+                    'include_static_file' => $include,
                     'constants' => $constants
                 ])
                 ->execute();
@@ -367,9 +421,6 @@ class SiteController extends ActionController
             // Create the site config.yaml file
             $this->writeConfigFile($organizationId, $rootUid, $domain);
 
-            // Create the BE user
-            // -- BE user will be auto-updated by the ot_connect extension --
-
             // Create the user_upload directory and update the sys_filemounts table
             $uploadRelPath = "/user_upload/" . $organizationId;
             $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
@@ -401,7 +452,13 @@ class SiteController extends ActionController
                 ->execute();
 
             // Create the BE User
-            $beUid = $this->createBeUser($organizationId, $rootUid, $domain);
+            // -- NB: this user will then be auto-updated by the ot_connect extension --
+            $beUserUid = $this->createBeUser(
+                $organizationId,
+                $rootUid,
+                $domain,
+                $organizationExtraData['admin']
+            );
 
             // Give the keys of the website to this user (makes him the owner)
             $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
@@ -409,7 +466,7 @@ class SiteController extends ActionController
                 $queryBuilder
                     ->update('pages')
                     ->where($queryBuilder->expr()->eq('uid', $uid))
-                    ->set('perms_userid', $beUid)
+                    ->set('perms_userid', $beUserUid)
                     ->execute();
             }
 
@@ -418,7 +475,7 @@ class SiteController extends ActionController
             if (!$commitSuccess) {
                 throw new \RuntimeException('Something went wrong while commiting the result');
             }
-            return $rootUid;
+
 
         } catch(\Exception $e) {
             // rollback
@@ -437,6 +494,11 @@ class SiteController extends ActionController
 
             throw $e;
         }
+
+        // Extra steps that do not need any rollback:
+        $this->enableFeEditing($beUserUid);
+
+        return $rootUid;
     }
 
     /**
@@ -449,7 +511,12 @@ class SiteController extends ActionController
     public function updateSiteConstantsAction(int $organizationId) {
         $rootUid = $this->findRootUidFor($organizationId);
 
-        $constants = $this->genTemplateConstants($organizationId);
+        // This extra-data can not be retrieved from the API for now, but
+        // this shall be set up as soon as possible, to avoid requesting
+        // the prod-back DB directly.
+        $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
+
+        $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
 
         $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
         $queryBuilder
@@ -512,6 +579,11 @@ class SiteController extends ActionController
             $this->delete('pages', 'uid', $rootUid, $hard);
             $this->delete('sys_template', 'pid', $rootUid, $hard);
 
+            if ($hard) {
+                // there is no 'deleted' field in sys_domain
+                $this->delete('sys_domain', 'pid', $rootUid, $hard);
+            }
+
             // remove filemounts
             $this->delete('sys_filemounts',
                 'path',
@@ -593,13 +665,13 @@ class SiteController extends ActionController
                 if (is_dir(dirname($configYamlFile))) {
                     rmdir(dirname($configYamlFile));
                 }
-                if (is_dir(dirname($uploadDir . 'images'))) {
+                if (is_dir($uploadDir . 'images')) {
                     rmdir($uploadDir . 'images');
                 }
-                if (is_dir(dirname($uploadDir . 'Forms'))) {
+                if (is_dir($uploadDir . 'Forms')) {
                     rmdir($uploadDir . 'Forms');
                 }
-                if (is_dir(dirname($uploadDir))) {
+                if (is_dir($uploadDir)) {
                     rmdir($uploadDir);
                 }
             } else {
@@ -620,7 +692,7 @@ class SiteController extends ActionController
         } catch(\Exception $e) {
             // rollback
             $this->cnnPool->getConnectionByName('Default')->rollback();
-            if ($hard) {
+            if (!$hard) {
                 foreach ($renamed as $initialPath => $newPath) {
                     rename($newPath, $initialPath);
                 }
@@ -628,7 +700,6 @@ class SiteController extends ActionController
             if (file_exists($confirm_file)) {
                 unlink($confirm_file);
             }
-
             throw $e;
         }
     }
@@ -988,15 +1059,7 @@ class SiteController extends ActionController
             ->execute();
     }
 
-    /**
-     * Return the content of `sys_template`.`constants` of
-     * the website of the given organization
-     *
-     * @param int $organizationId
-     * @return string
-     */
-    private function genTemplateConstants(int $organizationId) {
-        $rootUid = null;
+    private function fetchOrganizationExtraData(int $organizationId) {
 
         $cnn = new PDO(
             "mysql:host=prod-back;dbname=opentalent",
@@ -1015,7 +1078,8 @@ class SiteController extends ActionController
         );
         $stmt->execute();
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
-        $org_data = $stmt->fetch();
+        $data = $stmt->fetch();
+
 
         $stmt = $cnn->prepare(
             "SELECT c.email 
@@ -1027,7 +1091,7 @@ class SiteController extends ActionController
         );
         $stmt->execute();
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
-        $contact = $stmt->fetch();
+        $data['email'] = $stmt->fetch()['email'];
 
         $stmt = $cnn->prepare(
             "SELECT n.name, n.logo, n.url 
@@ -1042,28 +1106,52 @@ class SiteController extends ActionController
         );
         $stmt->execute();
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
-        $network = $stmt->fetch();
+        $data['network'] = $stmt->fetch();
+
+        $stmt = $cnn->prepare(
+            "SELECT p.username, a.id, s.product
+                      FROM opentalent.Person p 
+                        INNER JOIN Access a ON p.id = a.person_id
+                        INNER JOIN Settings s on a.organization_id = s.organization_id
+                      where a.organization_id=" . $organizationId . " AND  a.adminAccess=1;"
+        );
+        $stmt->execute();
+        $stmt->setFetchMode(PDO::FETCH_ASSOC);
+        $data['admin'] = $stmt->fetch();
 
+        return $data;
+    }
+
+    /**
+     * Return the content of `sys_template`.`constants` of
+     * the website of the given organization
+     *
+     * @param int $organizationId
+     * @param array $organizationExtraData
+     * @return string
+     */
+    private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
         return "plugin.tx_ottemplating {\n" .
             "    settings {\n" .
             "        organization {\n" .
             "            id = " . $organizationId . "\n" .
-            "            name = " . $org_data['name'] . "\n" .
-            "            is_network = " . ($org_data['category'] == 'NETWORK' ? '1' : '0') . "\n" .
-            "            email = " . $contact['email'] . "\n" .
-            "            logoid = " . $org_data['logo_id'] . "\n" .
-            "            twitter = " . $org_data['twitter'] . "\n" .
-            "            facebook = " . $org_data['facebook'] . "\n" .
+            "            name = " . $organizationExtraData['name'] . "\n" .
+            "            is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
+            "            email = " . $organizationExtraData['email'] . "\n" .
+            "            logoid = " . $organizationExtraData['logo_id'] . "\n" .
+            "            twitter = " . $organizationExtraData['twitter'] . "\n" .
+            "            facebook = " . $organizationExtraData['facebook'] . "\n" .
             "        }\n" .
             "    network {\n" .
-            "            logo = " . $network['logo'] . "\n" .
-            "            name = " . $network['name'] . "\n" .
-            "            url = " . $network['url'] . "\n" .
+            "            logo = " . $organizationExtraData['network']['logo'] . "\n" .
+            "            name = " . $organizationExtraData['network']['name'] . "\n" .
+            "            url = " . $organizationExtraData['network']['url'] . "\n" .
             "        }\n" .
             "    }\n" .
             "}";
     }
 
+
     /**
      * Create the given directory, give its property to the www-data group and
      * record it as a newly created dir (for an eventual rollback)
@@ -1115,11 +1203,11 @@ class SiteController extends ActionController
             'baseVariants'=>[],
             'errorHandling'=>[
                 ['errorCode'=>'404',
-                    'errorHandler'=>'Page',
-                    'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']],
+                    'errorHandler'=>'PHP',
+                    'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
                 ['errorCode'=>'403',
-                    'errorHandler'=>'Page',
-                    'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']]
+                    'errorHandler'=>'PHP',
+                    'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
             ],
             'flux_content_types'=>'',
             'flux_page_templates'=>'',
@@ -1155,29 +1243,15 @@ class SiteController extends ActionController
      * @param int $organizationId
      * @param int $rootUid
      * @param string $domain
+     * @param array $userData
      * @return int
      */
-    private function createBeUser(int $organizationId, int $rootUid, string $domain) {
-        $cnn = new PDO(
-            "mysql:host=prod-back;dbname=opentalent",
-            'dbcloner',
-            'wWZ4hYcrmHLW2mUK',
-            array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
-        );
-        $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+    private function createBeUser(int $organizationId,
+                                  int $rootUid,
+                                  string $domain,
+                                  array $userData) {
 
-        $stmt = $cnn->prepare(
-            "SELECT p.username, a.id, s.product
-                      FROM opentalent.Person p 
-                        INNER JOIN Access a ON p.id = a.person_id
-                        INNER JOIN Settings s on a.organization_id = s.organization_id
-                      where a.organization_id=" . $organizationId . " AND  a.adminAccess=1;"
-        );
-        $stmt->execute();
-        $stmt->setFetchMode(PDO::FETCH_ASSOC);
-        $user_data = $stmt->fetch();
-
-        if (!$user_data) {
+        if (!isset($userData['username'])) {
             throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
         }
 
@@ -1198,17 +1272,17 @@ class SiteController extends ActionController
         }
 
         $values = [
-            'username' => $user_data['username'],
+            'username' => $userData['username'],
             'password' => $randomStr,
-            'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $user_data['id'] . ')',
+            'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
             'deleted' => 0,
             'lang' => 'fr',
-            'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$user_data['product']] : 1,
+            'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
             'db_mountpoints' => $rootUid,
             'file_mountPoints' => join(',', $files),
             'options' => 2,
             'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
-            'tx_opentalent_opentalentId' => $user_data['id'],
+            'tx_opentalent_opentalentId' => $userData['id'],
             'tx_opentalent_organizationId' => $organizationId,
             'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
         ];
@@ -1218,17 +1292,21 @@ class SiteController extends ActionController
             ->values($values)
             ->execute();
 
-        $beUid = $queryBuilder->getConnection()->lastInsertId();
+        return $queryBuilder->getConnection()->lastInsertId();
+    }
 
-        // enable frontend editing
+    /**
+     * Enable frontend editing for user
+     *
+     * @param int $adminUid
+     */
+    private function enableFeEditing(int $adminUid) {
         $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
-        $user = $BE_USER->getRawUserByUid($beUid);
+        $user = $BE_USER->getRawUserByUid($adminUid);
         $BE_USER->user = $user;
         $BE_USER->backendSetUC();
         $BE_USER->uc['frontend_editing'] = 1;
         $BE_USER->uc['frontend_editing_overlay'] = 1;
         $BE_USER->writeUC($BE_USER->uc);
-
-        return $beUid;
     }
 }