From 191a017d96817124ddb94651d26860bdabc736f1 Mon Sep 17 00:00:00 2001
From: Morton Jonuschat <m.jonuschat@mojocode.de>
Date: Fri, 23 Oct 2015 16:31:11 +0200
Subject: [PATCH] [TASK] Use dedicated database field for `textmedia` media
 references

To avoid side effects and make maintenance easier the textmedia content
element from EXT:fluid_styled_content uses a dedicated field for media
file references This avoids side effects with EXT:css_styled_content as
the child TCA of the file references is no longer depended on the parent
CType configuration.

This also fixes the wrong media palette being shown in the backend as
the AJAX call to fetch the inline record does not have access to th
parent record.

An upgrade wizard is provided to migrate the file references to the new
assets database field.

Resolves: #70957
Releases: master
Change-Id: I32d7284e2098b4ab74f10f1fc8c7d07a7553511d
Reviewed-on: https://review.typo3.org/44228
Reviewed-by: Christian Kuhn <lolli@schwarzbu.ch>
Tested-by: Christian Kuhn <lolli@schwarzbu.ch>
Reviewed-by: Anja Leichsenring <aleichsenring@ab-softlab.de>
Tested-by: Anja Leichsenring <aleichsenring@ab-softlab.de>
---
 .../Hooks/TextmediaPreviewRenderer.php        |  6 +-
 .../TCA/Overrides/tt_content.php              | 28 +++---
 .../Static/Setup/lib.fluidContent.ts          |  2 +-
 .../Configuration/TypoScript/Static/setup.txt |  4 +-
 .../Resources/Private/Language/Database.xlf   |  4 +-
 .../fluid_styled_content/ext_tables.sql       |  3 +-
 .../Updates/ContentTypesToTextMediaUpdate.php |  6 +-
 .../MigrateMediaToAssetsForTextMediaCe.php    | 99 +++++++++++++++++++
 typo3/sysext/install/ext_localconf.php        |  1 +
 9 files changed, 126 insertions(+), 27 deletions(-)
 create mode 100644 typo3/sysext/install/Classes/Updates/MigrateMediaToAssetsForTextMediaCe.php

diff --git a/typo3/sysext/fluid_styled_content/Classes/Hooks/TextmediaPreviewRenderer.php b/typo3/sysext/fluid_styled_content/Classes/Hooks/TextmediaPreviewRenderer.php
index 8e5bf7e737e0..4975587db5f6 100644
--- a/typo3/sysext/fluid_styled_content/Classes/Hooks/TextmediaPreviewRenderer.php
+++ b/typo3/sysext/fluid_styled_content/Classes/Hooks/TextmediaPreviewRenderer.php
@@ -46,10 +46,10 @@ class TextmediaPreviewRenderer implements PageLayoutViewDrawItemHookInterface
                 $itemContent .= $parentObject->linkEditContent($parentObject->renderText($row['bodytext']), $row) . '<br />';
             }
 
-            if ($row['media']) {
-                $itemContent .= $parentObject->linkEditContent($parentObject->getThumbCodeUnlinked($row, 'tt_content', 'media'), $row) . '<br />';
+            if ($row['assets']) {
+                $itemContent .= $parentObject->linkEditContent($parentObject->getThumbCodeUnlinked($row, 'tt_content', 'assets'), $row) . '<br />';
 
-                $fileReferences = BackendUtility::resolveFileReferences('tt_content', 'media', $row);
+                $fileReferences = BackendUtility::resolveFileReferences('tt_content', 'assets', $row);
 
                 if (!empty($fileReferences)) {
                     $linkedContent = '';
diff --git a/typo3/sysext/fluid_styled_content/Configuration/TCA/Overrides/tt_content.php b/typo3/sysext/fluid_styled_content/Configuration/TCA/Overrides/tt_content.php
index 6f1754874ba6..18789b51a7ef 100644
--- a/typo3/sysext/fluid_styled_content/Configuration/TCA/Overrides/tt_content.php
+++ b/typo3/sysext/fluid_styled_content/Configuration/TCA/Overrides/tt_content.php
@@ -40,7 +40,7 @@ call_user_func(function () {
 				--palette--;' . $frontendLanguageFilePrefix . 'palette.header;header,
 				bodytext;' . $frontendLanguageFilePrefix . 'bodytext_formlabel;;richtext:rte_transform[mode=ts_css],
 			--div--;' . $frontendLanguageFilePrefix . 'tabs.media,
-				media,
+				assets,
 				--palette--;' . $frontendLanguageFilePrefix . 'palette.imagelinks;imagelinks,
 			--div--;' . $frontendLanguageFilePrefix . 'tabs.appearance,
 				layout;' . $frontendLanguageFilePrefix . 'layout_formlabel,
@@ -52,19 +52,6 @@ call_user_func(function () {
 				--palette--;' . $frontendLanguageFilePrefix . 'palette.access;access,
 			--div--;' . $frontendLanguageFilePrefix . 'tabs.extended
 		',
-        'columnsOverrides' => [
-            'media' => [
-                'label' => $languageFilePrefix . 'tt_content.media_references',
-                'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('media', [
-                    'appearance' => [
-                        'createNewRelationLinkTitle' => $languageFilePrefix . 'tt_content.media_references.addFileReference'
-                    ],
-                    // custom configuration for displaying fields in the overlay/reference table
-                    // behaves the same as the image field.
-                    'foreign_types' => $GLOBALS['TCA']['tt_content']['columns']['image']['config']['foreign_types']
-                ], $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext'])
-            ]
-        ]
     ];
 
     // Add category tab when categories column exits
@@ -117,7 +104,18 @@ call_user_func(function () {
                 ],
                 'default' => 0
             ]
-        ]
+        ],
+        'assets' => [
+            'label' => $languageFilePrefix . 'tt_content.asset_references',
+            'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('assets', [
+                'appearance' => [
+                    'createNewRelationLinkTitle' => $languageFilePrefix . 'tt_content.asset_references.addFileReference'
+                ],
+                // custom configuration for displaying fields in the overlay/reference table
+                // behaves the same as the image field.
+                'foreign_types' => $GLOBALS['TCA']['tt_content']['columns']['image']['config']['foreign_types']
+            ], $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext'])
+        ],
     ];
 
     \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content', $additionalColumns);
diff --git a/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/Setup/lib.fluidContent.ts b/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/Setup/lib.fluidContent.ts
index 3b6a1f4f3262..5ba9938a9e9e 100644
--- a/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/Setup/lib.fluidContent.ts
+++ b/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/Setup/lib.fluidContent.ts
@@ -34,4 +34,4 @@ lib.fluidContent {
 			}
 		}
 	}
-}
\ No newline at end of file
+}
diff --git a/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/setup.txt b/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/setup.txt
index 260d191b9a32..9e8e0f8d3087 100644
--- a/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/setup.txt
+++ b/typo3/sysext/fluid_styled_content/Configuration/TypoScript/Static/setup.txt
@@ -174,7 +174,7 @@ tt_content {
 		dataProcessing {
 			10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
 			10 {
-				references.fieldName = media
+				references.fieldName = assets
 			}
 			20 = TYPO3\CMS\Frontend\DataProcessing\GalleryProcessor
 			20 {
@@ -187,7 +187,7 @@ tt_content {
 		}
 		stdWrap {
 			# Setup the edit icon for content element "textmedia"
-			editIcons = tt_content: header [header_layout], bodytext, media [imageorient|imagewidth|imageheight], [imagecols|imageborder], image_zoom
+			editIcons = tt_content: header [header_layout], bodytext, assets [imageorient|imagewidth|imageheight], [imagecols|imageborder], image_zoom
 			editIcons {
 				iconTitle.data = LLL:EXT:fluid_styled_content/Resources/Private/Language/FrontendEditing.xlf:editIcon.textmedia
 			}
diff --git a/typo3/sysext/fluid_styled_content/Resources/Private/Language/Database.xlf b/typo3/sysext/fluid_styled_content/Resources/Private/Language/Database.xlf
index 1b3e6e89d76f..138c578e7cb0 100644
--- a/typo3/sysext/fluid_styled_content/Resources/Private/Language/Database.xlf
+++ b/typo3/sysext/fluid_styled_content/Resources/Private/Language/Database.xlf
@@ -48,10 +48,10 @@
 			<trans-unit id="tt_content.palette.mediaAdjustments">
 				<source>Media Adjustments</source>
 			</trans-unit>
-			<trans-unit id="tt_content.media_references">
+			<trans-unit id="tt_content.asset_references">
 				<source>Media elements</source>
 			</trans-unit>
-			<trans-unit id="tt_content.media_references.addFileReference">
+			<trans-unit id="tt_content.asset_references.addFileReference">
 				<source>Add media file</source>
 			</trans-unit>
 		</body>
diff --git a/typo3/sysext/fluid_styled_content/ext_tables.sql b/typo3/sysext/fluid_styled_content/ext_tables.sql
index 163cc3f0cb36..a1c5df06076f 100644
--- a/typo3/sysext/fluid_styled_content/ext_tables.sql
+++ b/typo3/sysext/fluid_styled_content/ext_tables.sql
@@ -4,5 +4,6 @@
 CREATE TABLE tt_content (
 	bullets_type tinyint(3) unsigned DEFAULT '0' NOT NULL,
 	uploads_description tinyint(1) unsigned DEFAULT '0' NOT NULL,
-	uploads_type tinyint(3) unsigned DEFAULT '0' NOT NULL
+	uploads_type tinyint(3) unsigned DEFAULT '0' NOT NULL,
+	assets int(11) unsigned DEFAULT '0' NOT NULL,
 );
diff --git a/typo3/sysext/install/Classes/Updates/ContentTypesToTextMediaUpdate.php b/typo3/sysext/install/Classes/Updates/ContentTypesToTextMediaUpdate.php
index 3aefbe133a56..ccb1ee1c0101 100644
--- a/typo3/sysext/install/Classes/Updates/ContentTypesToTextMediaUpdate.php
+++ b/typo3/sysext/install/Classes/Updates/ContentTypesToTextMediaUpdate.php
@@ -97,9 +97,9 @@ class ContentTypesToTextMediaUpdate extends AbstractUpdate
 			AND sys_file_reference.tablenames =\'tt_content\'
 			AND sys_file_reference.fieldname = \'image\'
 			SET tt_content.CType = \'textmedia\',
-			tt_content.media = image,
-			tt_content.image = \'\',
-			sys_file_reference.fieldname = \'media\'
+			tt_content.assets = image,
+			tt_content.image = 0,
+			sys_file_reference.fieldname = \'assets\'
 			WHERE
 			tt_content.CType = \'textpic\'
 			OR tt_content.CType = \'image\'
diff --git a/typo3/sysext/install/Classes/Updates/MigrateMediaToAssetsForTextMediaCe.php b/typo3/sysext/install/Classes/Updates/MigrateMediaToAssetsForTextMediaCe.php
new file mode 100644
index 000000000000..d38927943249
--- /dev/null
+++ b/typo3/sysext/install/Classes/Updates/MigrateMediaToAssetsForTextMediaCe.php
@@ -0,0 +1,99 @@
+<?php
+namespace TYPO3\CMS\Install\Updates;
+
+/*
+ * This file is part of the TYPO3 CMS project.
+ *
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
+ *
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
+ *
+ * The TYPO3 project - inspiring people to share!
+ */
+
+/**
+ * Migrate CTypes 'textmedia' to use 'assets' field instead of 'media'
+ */
+class MigrateMediaToAssetsForTextMediaCe extends AbstractUpdate
+{
+    /**
+     * @var string
+     */
+    protected $title = 'Migrate CTypes textmedia database field "media" to "assets"';
+
+    /**
+     * Checks if an update is needed
+     *
+     * @param string &$description The description for the update
+     * @return bool Whether an update is needed (TRUE) or not (FALSE)
+     */
+    public function checkForUpdate(&$description)
+    {
+        $updateNeeded = true;
+
+        if ($this->isWizardDone()) {
+            $updateNeeded = false;
+        } else {
+            // No need to join the sys_file_references table here as we can rely on the reference
+            // counter to check if the wizards has any textmedia content elements to upgrade.
+            $textmediaCount = $this->getDatabaseConnection()->exec_SELECTcountRows(
+                'uid',
+                'tt_content',
+                'CType = \'textmedia\' AND media > 0'
+            );
+
+            if ($textmediaCount === 0) {
+                $updateNeeded = false;
+                $this->markWizardAsDone();
+            }
+        }
+
+        $description = 'The extension "fluid_styled_content" is using a new database field for mediafile references. ' .
+            'This update wizard migrates these old references to use the new database field.';
+
+        return $updateNeeded;
+    }
+
+    /**
+     * Performs the database update if old mediafile references are available
+     *
+     * @param array &$databaseQueries Queries done in this update
+     * @param mixed &$customMessages Custom messages
+     * @return bool
+     */
+    public function performUpdate(array &$databaseQueries, &$customMessages)
+    {
+        $databaseConnection = $this->getDatabaseConnection();
+
+        // Update 'textmedia'
+        $query = '
+			UPDATE sys_file_reference
+			LEFT JOIN tt_content
+			ON sys_file_reference.uid_foreign = tt_content.uid
+			AND sys_file_reference.tablenames =\'tt_content\'
+			AND sys_file_reference.fieldname = \'media\'
+			SET tt_content.assets = tt_content.media,
+			tt_content.media = 0,
+			sys_file_reference.fieldname = \'assets\'
+			WHERE
+			tt_content.CType = \'textmedia\'
+			AND tt_content.media > 0
+		';
+        $databaseConnection->sql_query($query);
+
+        // Store last executed query
+        $databaseQueries[] = str_replace(chr(10), ' ', $query);
+        // Check for errors
+        if ($databaseConnection->sql_error()) {
+            $customMessages = 'SQL-ERROR: ' . htmlspecialchars($databaseConnection->sql_error());
+            return false;
+        }
+
+        $this->markWizardAsDone();
+
+        return true;
+    }
+}
diff --git a/typo3/sysext/install/ext_localconf.php b/typo3/sysext/install/ext_localconf.php
index a1e3c939ef94..622d23b1e6f7 100644
--- a/typo3/sysext/install/ext_localconf.php
+++ b/typo3/sysext/install/ext_localconf.php
@@ -12,6 +12,7 @@ $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update']['tableCType']
 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'][\TYPO3\CMS\Install\Updates\FileListIsStartModuleUpdate::class] = \TYPO3\CMS\Install\Updates\FileListIsStartModuleUpdate::class;
 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update']['textmediaCType'] = \TYPO3\CMS\Install\Updates\ContentTypesToTextMediaUpdate::class;
 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'][\TYPO3\CMS\Install\Updates\WorkspacesNotificationSettingsUpdate::class] = \TYPO3\CMS\Install\Updates\WorkspacesNotificationSettingsUpdate::class;
+$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update']['textmediaAssets'] = \TYPO3\CMS\Install\Updates\MigrateMediaToAssetsForTextMediaCe::class;
 
 $signalSlotDispatcher = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
 $signalSlotDispatcher->connect(
-- 
GitLab