Skip to content

Commit

Permalink
[TASK] Respect rte allow tags in translate request
Browse files Browse the repository at this point in the history
With this change the RTE configuration is determined from the field to be translated.
To give deepl a list of allowed HTML tags.
To allow a correct separation in the translated text with HTML tag.
  • Loading branch information
NarkNiro committed Jul 28, 2023
1 parent ffbcc23 commit 2187a72
Show file tree
Hide file tree
Showing 13 changed files with 379 additions and 74 deletions.
13 changes: 8 additions & 5 deletions Classes/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use WebVision\WvDeepltranslate\Domain\Dto\TranslateOptions;
use WebVision\WvDeepltranslate\Exception\ClientNotValidUrlException;

final class Client
Expand All @@ -31,15 +32,15 @@ public function __construct()
$this->requestFactory = GeneralUtility::makeInstance(RequestFactory::class);
}

public function translate(string $content, string $sourceLang, string $targetLang, string $glossary = ''): ResponseInterface
{
public function translate(
string $content,
TranslateOptions $options,
string $glossary = ''
): ResponseInterface {
$baseUrl = $this->buildBaseUrl('translate');

$postFields = [
'text' => $content,
'source_lang' => $sourceLang,
'target_lang' => $targetLang,
'tag_handling' => 'xml',
];

if (!empty($glossary)) {
Expand All @@ -48,6 +49,8 @@ public function translate(string $content, string $sourceLang, string $targetLan

$postFields['formality'] = $this->configuration->getFormality();

$postFields = array_merge($postFields, $options->toArray());

return $this->requestFactory->request($baseUrl, 'POST', $this->mergeRequiredRequestOptions([
'form_params' => $postFields,
]));
Expand Down
124 changes: 124 additions & 0 deletions Classes/Domain/Dto/TranslateOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php

declare(strict_types=1);

namespace WebVision\WvDeepltranslate\Domain\Dto;

/**
* @internal
*/
final class TranslateOptions
{
protected string $splitSentences = 'nonewlines';

protected bool $outlineDetection = false;

protected array $splittingTags = [];

protected array $nonSplittingTags = [];

protected array $ignoreTags = [];

protected string $tagHandling = 'xml';

protected string $targetLanguage;

protected string $sourceLanguage;

public function getSplitSentences(): string
{
return $this->splitSentences;
}

public function setSplitSentences(string $splitSentences): void
{
$this->splitSentences = $splitSentences;
}

public function isOutlineDetection(): bool
{
return $this->outlineDetection;
}

public function setOutlineDetection(bool $outlineDetection): void
{
$this->outlineDetection = $outlineDetection;
}

public function getSplittingTags(): array
{
return $this->splittingTags;
}

public function setSplittingTags(array $splittingTags): void
{
$this->splittingTags = $splittingTags;
}

public function getNonSplittingTags(): array
{
return $this->nonSplittingTags;
}

public function setNonSplittingTags(array $nonSplittingTags): void
{
$this->nonSplittingTags = $nonSplittingTags;
}

public function getIgnoreTags(): array
{
return $this->ignoreTags;
}

public function setIgnoreTags(array $ignoreTags): void
{
$this->ignoreTags = $ignoreTags;
}

public function getTagHandling(): string
{
return $this->tagHandling;
}

public function setTagHandling(string $tagHandling): void
{
$this->tagHandling = $tagHandling;
}

public function getTargetLanguage(): string
{
return $this->targetLanguage;
}

public function setTargetLanguage(string $targetLanguage): void
{
$this->targetLanguage = $targetLanguage;
}

public function getSourceLanguage(): string
{
return $this->sourceLanguage;
}

public function setSourceLanguage(string $sourceLanguage): void
{
$this->sourceLanguage = $sourceLanguage;
}

public function toArray(): array
{
$param = [];
$param['tag_handling'] = $this->tagHandling;

if (!empty($this->splittingTags)) {
$param['outlineDetection'] = $this->outlineDetection;
$param['split_sentences'] = $this->splitSentences;
$param['splitting_tags'] = implode(',', $this->splittingTags);
}

$param['source_lang'] = $this->sourceLanguage;
$param['target_lang'] = $this->targetLanguage;

return $param;
}
}
57 changes: 27 additions & 30 deletions Classes/Hooks/TranslateHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use WebVision\WvDeepltranslate\Domain\Dto\TranslateOptions;
use WebVision\WvDeepltranslate\Domain\Repository\PageRepository;
use WebVision\WvDeepltranslate\Domain\Repository\SettingsRepository;
use WebVision\WvDeepltranslate\Exception\LanguageIsoCodeNotFoundException;
use WebVision\WvDeepltranslate\Exception\LanguageRecordNotFoundException;
use WebVision\WvDeepltranslate\Resolver\RichtextAllowTagsResolver;
use WebVision\WvDeepltranslate\Service\DeeplService;
use WebVision\WvDeepltranslate\Service\GoogleTranslateService;
use WebVision\WvDeepltranslate\Service\LanguageService;
Expand All @@ -24,31 +24,31 @@ class TranslateHook

protected GoogleTranslateService $googleService;

protected SettingsRepository $deeplSettingsRepository;

protected PageRepository $pageRepository;

private LanguageService $languageService;

public function __construct(
?SettingsRepository $settingsRepository = null,
?PageRepository $pageRepository = null,
?DeeplService $deeplService = null,
?GoogleTranslateService $googleService = null
?GoogleTranslateService $googleService = null,
?LanguageService $languageService = null
) {
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$this->deeplSettingsRepository = $settingsRepository ?? $objectManager->get(SettingsRepository::class);
$this->deeplService = $deeplService ?? $objectManager->get(DeeplService::class);
$this->googleService = $googleService ?? $objectManager->get(GoogleTranslateService::class);
$this->deeplService = $deeplService ?? GeneralUtility::makeInstance(DeeplService::class);
$this->pageRepository = $pageRepository ?? GeneralUtility::makeInstance(PageRepository::class);
$this->languageService = GeneralUtility::makeInstance(LanguageService::class);
$this->languageService = $languageService ?? GeneralUtility::makeInstance(LanguageService::class);
$this->googleService = $googleService ?? GeneralUtility::makeInstance(GoogleTranslateService::class);
}

/**
* @param array{uid: int} $languageRecord
*/
public function processTranslateTo_copyAction(string &$content, array $languageRecord, DataHandler $dataHandler): string
{
public function processTranslateTo_copyAction(
string &$content,
array $languageRecord,
DataHandler $dataHandler,
string $columnName
): string {
$tableName = '';
$currentRecordId = '';

Expand All @@ -62,12 +62,7 @@ public function processTranslateTo_copyAction(string &$content, array $languageR
break;
}

if (!isset($cmdmap['localization']['custom']['srcLanguageId'])) {
$cmdmap['localization']['custom']['srcLanguageId'] = '';
}

$customMode = $cmdmap['localization']['custom']['mode'] ?? null;
[$sourceLanguage,] = explode('-', (string)$cmdmap['localization']['custom']['srcLanguageId']);

//translation mode set to deepl or google translate
if ($customMode === null) {
Expand All @@ -79,21 +74,28 @@ public function processTranslateTo_copyAction(string &$content, array $languageR
$translatedContent = '';
$targetLanguageRecord = [];

$translateOptions = GeneralUtility::makeInstance(TranslateOptions::class);
$richtextAllowTagsResolver = GeneralUtility::makeInstance(RichtextAllowTagsResolver::class);
$translateOptions->setSplittingTags(
$richtextAllowTagsResolver->resolve($tableName, $currentRecordId, $columnName)
);

try {
$sourceLanguageRecord = $this->languageService->getSourceLanguage(
$siteInformation['site']
);
$translateOptions->setSourceLanguage($sourceLanguageRecord['language_isocode']);

$targetLanguageRecord = $this->languageService->getTargetLanguage(
$siteInformation['site'],
(int)$languageRecord['uid']
);
$translateOptions->setTargetLanguage($targetLanguageRecord['language_isocode']);

$translatedContent = $this->translateContent(
$content,
$targetLanguageRecord,
$translateOptions,
$customMode,
$sourceLanguageRecord
);
} catch (LanguageIsoCodeNotFoundException|LanguageRecordNotFoundException $e) {
$flashMessage = GeneralUtility::makeInstance(
Expand Down Expand Up @@ -123,22 +125,17 @@ public function processTranslateTo_copyAction(string &$content, array $languageR

/**
* These logics were outsourced to test them and later to resolve them in a service
*
* @param array{uid: int, language_isocode: string} $targetLanguageRecord
* @param array{uid: int, language_isocode: string} $sourceLanguageRecord
*/
public function translateContent(
string $content,
array $targetLanguageRecord,
string $customMode,
array $sourceLanguageRecord
TranslateOptions $translateOptions,
string $customMode
): string {
// mode deepl
if ($customMode == 'deepl') {
$response = $this->deeplService->translateRequest(
$content,
$targetLanguageRecord['language_isocode'],
$sourceLanguageRecord['language_isocode']
$translateOptions
);

if (!empty($response) && isset($response['translations'])) {
Expand All @@ -152,8 +149,8 @@ public function translateContent(
} //mode google
elseif ($customMode == 'google') {
$response = $this->googleService->translate(
$sourceLanguageRecord['language_isocode'],
$targetLanguageRecord['language_isocode'],
$translateOptions->getSourceLanguage(),
$translateOptions->getTargetLanguage(),
$content
);

Expand Down
57 changes: 57 additions & 0 deletions Classes/Resolver/RichtextAllowTagsResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace WebVision\WvDeepltranslate\Resolver;

use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Configuration\Richtext;
use TYPO3\CMS\Core\Utility\GeneralUtility;

final class RichtextAllowTagsResolver
{
private Richtext $richtext;

public function __construct(
?Richtext $richtext = null
) {
$this->richtext = $richtext ?? GeneralUtility::makeInstance(Richtext::class);
}

public function resolve(string $tableName, int $recordId, string $fieldName): array
{
if (!isset($GLOBALS['TCA'][$tableName]['columns'])) {
throw new \RuntimeException('TCA Columns ist not defined', 1689950520561);
}

$field = $GLOBALS['TCA'][$tableName]['columns'][$fieldName];

if (!isset($field['config']['type'])) {
return [];
}

if ($field['config']['type'] !== 'text') {
return [];
}

if (isset($field['config']['enableRichtext'])) {
if ($field['config']['enableRichtext'] === false) {
return [];
}
} elseif (isset($GLOBALS['TCA'][$tableName]['types']['columnsOverrides'][$fieldName]['config']['enableRichtext'])) {
if ($GLOBALS['TCA'][$tableName]['types']['columnsOverrides'][$fieldName]['config']['enableRichtext'] === false) {
return [];
}
}

$record = BackendUtility::getRecord($tableName, $recordId);

$allowTags = [];
$rteConfig = $this->richtext->getConfiguration($tableName, $fieldName, $record['pid'], $record['CType'], $field['config']);
if (isset($rteConfig['processing']['allowTags'])) {
$allowTags = array_unique(array_merge($allowTags, $rteConfig['processing']['allowTags']), SORT_REGULAR);
}

return $allowTags;
}
}
Loading

0 comments on commit 2187a72

Please sign in to comment.