Skip to content

Commit

Permalink
[BUGFIX] Display human-readable preview of FlexForm values
Browse files Browse the repository at this point in the history
This change transforms the processed record of FlexForms
into a human-readable format.

This is especially useful when comparing changes in the
history module or the workspaces diff view.

The diff needs to be formatted with line breaks and tabs as
the output is passed through "htmlspecialchars" before it
will be displayed.

The white-space css setting needs to be changed to
"pre-wrap", because this is the only setting where line
breaks and tabs are kept and the text will still be
word-wrapped.

The old view is used as a fallback, if no record is
available (import preview).

Resolves: #91148
Releases: main, 11.5
Change-Id: Iab1dfb59f98dc712b8984a8087525634b5ec4ebd
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/75075
Tested-by: core-ci <typo3@b13.com>
Tested-by: Nikita Hovratov <nikita.h@live.de>
Reviewed-by: Nikita Hovratov <nikita.h@live.de>
  • Loading branch information
utrotzek authored and nhovratov committed Jul 8, 2022
1 parent 57e84b7 commit f8a0020
Show file tree
Hide file tree
Showing 12 changed files with 639 additions and 13 deletions.
2 changes: 1 addition & 1 deletion Build/Sources/Sass/component/_diff.scss
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,6 @@ $diff-title-bgcolor: #fafafa;
}

&.diff-item-result-inline {
white-space: normal;
white-space: pre-wrap;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

namespace TYPO3\CMS\Backend\Controller\ContentElement;

use cogpowered\FineDiff\Diff;
use cogpowered\FineDiff\Granularity\Character;
use cogpowered\FineDiff\Granularity\Word;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\History\RecordHistory;
Expand Down Expand Up @@ -344,7 +347,7 @@ protected function displayHistory(array $historyEntries)
$singleLine['fieldNames'] = implode(',', $tmpFieldList);
} else {
// Display diff
$singleLine['differences'] = $this->renderDiff($entry, $entry['tablename']);
$singleLine['differences'] = $this->renderDiff($entry, $entry['tablename'], $entry['recuid']);
}
}
// put line together
Expand All @@ -371,11 +374,17 @@ protected function renderDiff($entry, $table, $rollbackUid = 0): array
$fieldsToDisplay = array_keys($entry['newRecord']);
$languageService = $this->getLanguageService();
foreach ($fieldsToDisplay as $fN) {
if (is_array($GLOBALS['TCA'][$table]['columns'][$fN] ?? null) && ($GLOBALS['TCA'][$table]['columns'][$fN]['config']['type'] ?? '') !== 'passthrough') {
$tcaType = $GLOBALS['TCA'][$table]['columns'][$fN]['config']['type'] ?? '';
if (is_array($GLOBALS['TCA'][$table]['columns'][$fN] ?? null) && $tcaType !== 'passthrough') {
// Create diff-result:
$diffres = $diffUtility->makeDiffDisplay(
BackendUtility::getProcessedValue($table, $fN, ($entry['oldRecord'][$fN] ?? ''), 0, true),
BackendUtility::getProcessedValue($table, $fN, ($entry['newRecord'][$fN] ?? ''), 0, true)
$granularity = new Word();
if ($tcaType === 'flex') {
$granularity = new Character();
}
$diff = new Diff($granularity);
$diffres = $diff->render(
strip_tags((string)BackendUtility::getProcessedValue($table, $fN, ($entry['oldRecord'][$fN] ?? ''), 0, true, false, $rollbackUid)),
strip_tags((string)BackendUtility::getProcessedValue($table, $fN, ($entry['newRecord'][$fN] ?? ''), 0, true, false, $rollbackUid))
);
$rollbackUrl = '';
if ($rollbackUid) {
Expand Down
8 changes: 7 additions & 1 deletion typo3/sysext/backend/Classes/Utility/BackendUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use TYPO3\CMS\Backend\Domain\Model\Element\ImmediateActionElement;
use TYPO3\CMS\Backend\Routing\Route;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\View\ValueFormatter\FlexFormValueFormatter;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
Expand Down Expand Up @@ -1723,7 +1724,12 @@ public static function getProcessedValue(
}
break;
case 'flex':
$l = strip_tags($value);
if ($uid) {
$flexFormValueFormatter = GeneralUtility::makeInstance(FlexFormValueFormatter::class);
$l = $flexFormValueFormatter->format($table, $col, $value, $uid, $theColConf);
} elseif (is_string($value)) {
$l = strip_tags($value);
}
break;
case 'language':
$l = $value;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
<?php

declare(strict_types=1);

/*
* 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!
*/

namespace TYPO3\CMS\Backend\View\ValueFormatter;

use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\StringUtility;

/**
* The FlexFormValueFormatter formats a FlexForm value into a human-readable
* format. This is used internally to display changes in FlexForm values as a
* nicely formatted plain-text diff.
*
* @internal
*/
class FlexFormValueFormatter
{
protected const VALUE_MAX_LENGTH = 50;

public function format(
string $tableName,
string $fieldName,
?string $value,
int $uid,
array $fieldConfiguration
): string {
if ($value === null || $value === '') {
return '';
}

$record = BackendUtility::getRecord($tableName, $uid) ?? [];

// Get FlexForm data and structure
$flexFormDataArray = GeneralUtility::xml2array($value);
$flexFormDataStructure = $this->getFlexFormDataStructure($fieldConfiguration, $tableName, $fieldName, $record);

// Map data to FlexForm structure and build an easy to handle array
$processedSheets = $this->getProcessedSheets($flexFormDataStructure, $flexFormDataArray['data']);

// Render a human-readable plain text representation of the FlexForm data
$renderedPlainValue = $this->renderFlexFormValuePlain($processedSheets);
return trim($renderedPlainValue, PHP_EOL);
}

/**
* @param array<string, mixed> $tcaConfiguration
* @param string $tableName
* @param string $fieldName
* @param array<string, mixed> $record
* @return array
*/
protected function getFlexFormDataStructure(
array $tcaConfiguration,
string $tableName,
string $fieldName,
array $record
): array {
$conf['config'] = $tcaConfiguration;
$flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
$flexFormIdentifier = $flexFormTools->getDataStructureIdentifier($conf, $tableName, $fieldName, $record);
return $flexFormTools->parseDataStructureByIdentifier($flexFormIdentifier);
}

/**
* @param array<string, mixed> $processedData
* @param int $currentHierarchy
* @return string
*/
protected function renderFlexFormValuePlain(array $processedData, int $currentHierarchy = 1): string
{
$value = '';
foreach ($processedData as $processedKey => $processedValue) {
$title = !empty($processedValue['section']) ? $processedKey : $processedValue['title'];

if (!empty($processedValue['children'])) {
$children = $this->renderFlexFormValuePlain($processedValue['children'], $currentHierarchy + 1);

if (empty($processedValue['section']) && empty($processedValue['container'])) {
$value .= $this->getSectionHeadline($title) . PHP_EOL . $children . PHP_EOL;
} elseif ($children) {
$value .= $children . PHP_EOL;
}
} elseif (isset($processedValue['value'])) {
$wrappedValue = $this->wrapValue($processedValue['value'], $title);
$colon = ':';
// Add space after colon, if it fits into one line.
if (!str_contains($wrappedValue, PHP_EOL)) {
$colon .= ' ';
}
$value .= $title . $colon . $wrappedValue . PHP_EOL . PHP_EOL;
}
}
return $value;
}

/**
* Get the formatted headline of a FlexForm section
*/
protected function getSectionHeadline(string $title): string
{
$sectionSpacer = str_repeat('-', self::VALUE_MAX_LENGTH);
return $title . PHP_EOL . $sectionSpacer;
}

protected function getProcessedSheets(array $dataStructure, array $valueStructure): array
{
$processedSheets = [];

foreach ($dataStructure['sheets'] as $sheetKey => $sheetStructure) {
if (!empty($sheetStructure['ROOT']['el'])) {
$sheetTitle = $sheetKey;
if (!empty($sheetStructure['ROOT']['TCEforms']['sheetTitle'])) {
$sheetTitle = $this->getLanguageObject()->sL($sheetStructure['ROOT']['TCEforms']['sheetTitle']);
}

if (!empty($valueStructure[$sheetKey]['lDEF'])) {
$processedElements = $this->getProcessedElements(
$sheetStructure['ROOT']['el'],
$valueStructure[$sheetKey]['lDEF']
);
$processedSheets[$sheetKey] = [
'title' => $sheetTitle,
'children' => $processedElements,
];
}
}
}

return $processedSheets;
}

protected function getProcessedElements(array $dataStructure, array $valueStructure): array
{
$processedElements = [];

// Values used to fake TCA
$processingTableValue = StringUtility::getUniqueId('processing');
$processingColumnValue = StringUtility::getUniqueId('processing');

foreach ($dataStructure as $elementKey => $elementStructure) {
$elementTitle = $this->getElementTitle($elementKey, $elementStructure);

if (($elementStructure['type'] ?? '') === 'array') {
// Render section or container
if (empty($valueStructure[$elementKey]['el'])) {
continue;
}

if (!empty($elementStructure['section'])) {
// Render section
$processedElements[$elementKey] = [
'section' => true,
'title' => $elementTitle,
'children' => $this->getProcessedSections(
$elementStructure['el'],
$valueStructure[$elementKey]['el']
),
];
} else {
// Render container
$processedElements[$elementKey] = [
'container' => true,
'title' => $elementTitle,
'children' => $this->getProcessedElements(
$elementStructure['el'],
$valueStructure[$elementKey]['el']
),
];
}
} elseif (!empty($elementStructure['TCEforms']['config'])) {
// Render plain elements
$relationTable = $this->getRelationTable($elementStructure['TCEforms']['config']);
$labelUserFunction = $relationTable !== null ? $this->getRelationLabelUserFunction($relationTable) : null;

if ($relationTable !== null && $labelUserFunction !== null) {
$parameters = [
'table' => $relationTable,
'row' => BackendUtility::getRecord($relationTable, $valueStructure[$elementKey]['vDEF']),
'title' => $valueStructure[$elementKey]['vDEF'],
];
GeneralUtility::callUserFunction($labelUserFunction, $parameters);
$processedValue = $parameters['title'];
} else {
$GLOBALS['TCA'][$processingTableValue]['columns'][$processingColumnValue]['config'] = $elementStructure['TCEforms']['config'];
$processedValue = BackendUtility::getProcessedValue(
$processingTableValue,
$processingColumnValue,
$valueStructure[$elementKey]['vDEF'] ?? '',
);
}

$processedElements[$elementKey] = [
'title' => $elementTitle,
'value' => $processedValue,
];
}
}

if (!empty($GLOBALS['TCA'][$processingTableValue])) {
unset($GLOBALS['TCA'][$processingTableValue]);
}

return $processedElements;
}

protected function getRelationTable(array $configuration): ?string
{
// If allowed tables is defined, but with only one(!) table:
if (($configuration['allowed'] ?? '') !== '' && !str_contains($configuration['allowed'], ',')) {
return $configuration['allowed'];
}

return $configuration['foreign_table'] ?? null;
}

/**
* @param string $relationTable
* @return non-empty-string|null
*/
protected function getRelationLabelUserFunction(string $relationTable): ?string
{
if (!empty($GLOBALS['TCA'][$relationTable]['ctrl']['label_userFunc'])) {
return $GLOBALS['TCA'][$relationTable]['ctrl']['label_userFunc'];
}

return null;
}

protected function getProcessedSections(array $dataStructure, array $valueStructure): array
{
$processedSections = [];

foreach ($valueStructure as $sectionValueIndex => $sectionValueStructure) {
$processedSections[$sectionValueIndex] = [
'section' => true,
'children' => $this->getProcessedElements(
$dataStructure,
$sectionValueStructure
),
];
}

return $processedSections;
}

protected function getElementTitle(string $key, array $structure): string
{
if (!empty($structure['TCEforms']['label'])) {
return $this->getLanguageObject()->sL($structure['TCEforms']['label']);
}

return $key;
}

protected function wrapValue(string $value, string $title): string
{
if ($value === '') {
return '';
}

// If the length of the value is equal or less than the maxlength, no wrapping is needed.
if ((mb_strlen($title) + mb_strlen($value)) <= self::VALUE_MAX_LENGTH) {
return $value;
}

// wordwrap the value and add an indention for each line.
$multilineIndention = "\t";
$value = PHP_EOL . $multilineIndention . $value;
$lines = explode(PHP_EOL, $value);
$newValue = '';
foreach (array_map('trim', $lines) as $line) {
if ($line !== '') {
$newValue .= PHP_EOL . $line;
}
}
$value = wordwrap($newValue, self::VALUE_MAX_LENGTH, PHP_EOL);
return str_replace(PHP_EOL, PHP_EOL . $multilineIndention, $value);
}

protected function getLanguageObject(): LanguageService
{
return $GLOBALS['LANG'];
}
}
2 changes: 1 addition & 1 deletion typo3/sysext/backend/Resources/Public/Css/backend.css

Large diffs are not rendered by default.

Loading

0 comments on commit f8a0020

Please sign in to comment.