[!!!][TASK] Remove FormEngine / TCA related deprecated code
[Packages/TYPO3.CMS.git] / typo3 / sysext / rte_ckeditor / Classes / Form / Element / RichTextElement.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\RteCKEditor\Form\Element;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Backend\Form\Element\AbstractFormElement;
19 use TYPO3\CMS\Backend\Routing\UriBuilder;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Localization\Locales;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\PathUtility;
24
25 /**
26 * Render rich text editor in FormEngine
27 */
28 class RichTextElement extends AbstractFormElement
29 {
30 /**
31 * Default field wizards enabled for this element.
32 *
33 * @var array
34 */
35 protected $defaultFieldWizard = [
36 'localizationStateSelector' => [
37 'renderType' => 'localizationStateSelector',
38 ],
39 'otherLanguageContent' => [
40 'renderType' => 'otherLanguageContent',
41 'after' => [
42 'localizationStateSelector'
43 ],
44 ],
45 'defaultLanguageDifferences' => [
46 'renderType' => 'defaultLanguageDifferences',
47 'after' => [
48 'otherLanguageContent',
49 ],
50 ],
51 ];
52
53 /**
54 * This property contains configuration related to the RTE
55 * But only the .editor configuration part
56 *
57 * @var array
58 */
59 protected $rteConfiguration = [];
60
61 /**
62 * Renders the ckeditor element
63 *
64 * @return array
65 * @throws \InvalidArgumentException
66 */
67 public function render() : array
68 {
69 $resultArray = $this->initializeResultArray();
70 $parameterArray = $this->data['parameterArray'];
71 $config = $parameterArray['fieldConf']['config'];
72
73 $fieldId = $this->sanitizeFieldId($parameterArray['itemFormElName']);
74 $itemFormElementName = $this->data['parameterArray']['itemFormElName'];
75
76 $value = $this->data['parameterArray']['itemFormElValue'] ?? '';
77
78 $fieldInformationResult = $this->renderFieldInformation();
79 $fieldInformationHtml = $fieldInformationResult['html'];
80 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
81
82 $fieldControlResult = $this->renderFieldControl();
83 $fieldControlHtml = $fieldControlResult['html'];
84 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
85
86 $fieldWizardResult = $this->renderFieldWizard();
87 $fieldWizardHtml = $fieldWizardResult['html'];
88 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
89
90 $attributes = [
91 'style' => 'display:none',
92 'data-formengine-validation-rules' => $this->getValidationDataAsJsonString($config),
93 'id' => $fieldId,
94 'name' => htmlspecialchars($itemFormElementName),
95 ];
96
97 $html = [];
98 $html[] = '<div class="formengine-field-item t3js-formengine-field-item">';
99 $html[] = $fieldInformationHtml;
100 $html[] = '<div class="form-control-wrap">';
101 $html[] = '<div class="form-wizards-wrap">';
102 $html[] = '<div class="form-wizards-element">';
103 $html[] = '<textarea ' . GeneralUtility::implodeAttributes($attributes, true) . '>';
104 $html[] = htmlspecialchars($value);
105 $html[] = '</textarea>';
106 $html[] = '</div>';
107 $html[] = '<div class="form-wizards-items-aside">';
108 $html[] = '<div class="btn-group">';
109 $html[] = $fieldControlHtml;
110 $html[] = '</div>';
111 $html[] = '</div>';
112 $html[] = '<div class="form-wizards-items-bottom">';
113 $html[] = $fieldWizardHtml;
114 $html[] = '</div>';
115 $html[] = '</div>';
116 $html[] = '</div>';
117 $html[] = '</div>';
118
119 $resultArray['html'] = implode(LF, $html);
120
121 $this->rteConfiguration = $config['richtextConfiguration']['editor'];
122 $resultArray['requireJsModules'] = [];
123 $resultArray['requireJsModules'][] = [
124 'ckeditor' => $this->getCkEditorRequireJsModuleCode($fieldId)
125 ];
126
127 return $resultArray;
128 }
129
130 /**
131 * Determine the contents language iso code
132 *
133 * @return string
134 */
135 protected function getLanguageIsoCodeOfContent(): string
136 {
137 $currentLanguageUid = $this->data['databaseRow']['sys_language_uid'];
138 if (is_array($currentLanguageUid)) {
139 $currentLanguageUid = $currentLanguageUid[0];
140 }
141 $contentLanguageUid = (int)max($currentLanguageUid, 0);
142 if ($contentLanguageUid) {
143 $contentLanguage = $this->data['systemLanguageRows'][$currentLanguageUid]['iso'];
144 } else {
145 $contentLanguage = $this->rteConfiguration['config']['defaultContentLanguage'] ?? 'en_US';
146 $languageCodeParts = explode('_', $contentLanguage);
147 $contentLanguage = strtolower($languageCodeParts[0]) . ($languageCodeParts[1] ? '_' . strtoupper($languageCodeParts[1]) : '');
148 // Find the configured language in the list of localization locales
149 $locales = GeneralUtility::makeInstance(Locales::class);
150 // If not found, default to 'en'
151 if (!in_array($contentLanguage, $locales->getLocales(), true)) {
152 $contentLanguage = 'en';
153 }
154 }
155 return $contentLanguage;
156 }
157
158 /**
159 * Gets the JavaScript code for CKEditor module
160 * Compiles the configuration, and then adds plugins
161 *
162 * @param string $fieldId
163 * @return string
164 */
165 protected function getCkEditorRequireJsModuleCode(string $fieldId) : string
166 {
167 $configuration = $this->prepareConfigurationForEditor();
168
169 $externalPlugins = '';
170 foreach ($this->getExtraPlugins() as $pluginName => $config) {
171 $configuration[$pluginName] = $config['config'];
172 $configuration['extraPlugins'] .= ',' . $pluginName;
173
174 $externalPlugins .= 'CKEDITOR.plugins.addExternal(';
175 $externalPlugins .= GeneralUtility::quoteJSvalue($pluginName) . ',';
176 $externalPlugins .= GeneralUtility::quoteJSvalue($config['resource']) . ',';
177 $externalPlugins .= '\'\');';
178 }
179
180 return 'function(CKEDITOR) {
181 ' . $externalPlugins . '
182 CKEDITOR.replace("' . $fieldId . '", ' . json_encode($configuration) . ');
183 require([\'TYPO3/CMS/Backend/FormEngine\'], function(FormEngine) {
184 CKEDITOR.instances.' . $fieldId . '.on(\'change\', function() {
185 CKEDITOR.instances.' . $fieldId . '.updateElement();
186 FormEngine.Validation.validate();
187 });
188 });
189 }';
190 }
191
192 /**
193 * Get configuration of external/additional plugins
194 *
195 * @return array
196 */
197 protected function getExtraPlugins(): array
198 {
199 $urlParameters = [
200 'P' => [
201 'table' => $this->data['tableName'],
202 'uid' => $this->data['databaseRow']['uid'],
203 'fieldName' => $this->data['fieldName'],
204 'recordType' => $this->data['recordTypeValue'],
205 'pid' => $this->data['effectivePid'],
206 ]
207 ];
208
209 $pluginConfiguration = [];
210 if (isset($this->rteConfiguration['externalPlugins']) && is_array($this->rteConfiguration['externalPlugins'])) {
211 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
212 foreach ($this->rteConfiguration['externalPlugins'] as $pluginName => $configuration) {
213 $pluginConfiguration[$pluginName] = [
214 'resource' => $this->resolveUrlPath($configuration['resource'])
215 ];
216 unset($configuration['resource']);
217
218 if ($configuration['route']) {
219 $configuration['routeUrl'] = (string)$uriBuilder->buildUriFromRoute($configuration['route'], $urlParameters);
220 }
221
222 $pluginConfiguration[$pluginName]['config'] = $configuration;
223 }
224 }
225 return $pluginConfiguration;
226 }
227
228 /**
229 * Add configuration to replace absolute EXT: paths with relative ones
230 * @param array $configuration
231 *
232 * @return array
233 */
234 protected function replaceAbsolutePathsToRelativeResourcesPath(array $configuration): array
235 {
236 foreach ($configuration as $key => $value) {
237 if (is_array($value)) {
238 $configuration[$key] = $this->replaceAbsolutePathsToRelativeResourcesPath($value);
239 } elseif (is_string($value) && substr($value, 0, 4) === 'EXT:') {
240 $configuration[$key] = $this->resolveUrlPath($value);
241 }
242 }
243 return $configuration;
244 }
245
246 /**
247 * Resolves an EXT: syntax file to an absolute web URL
248 *
249 * @param string $value
250 * @return string
251 */
252 protected function resolveUrlPath(string $value): string
253 {
254 $value = GeneralUtility::getFileAbsFileName($value);
255 return PathUtility::getAbsoluteWebPath($value);
256 }
257
258 /**
259 * Compiles the configuration set from the outside
260 * to have it easily injected into the CKEditor.
261 *
262 * @return array the configuration
263 */
264 protected function prepareConfigurationForEditor(): array
265 {
266 // Ensure custom config is empty so nothing additional is loaded
267 // Of course this can be overridden by the editor configuration below
268 $configuration = [
269 'customConfig' => '',
270 ];
271
272 if (is_array($this->rteConfiguration['config'])) {
273 $configuration = array_replace_recursive($configuration, $this->rteConfiguration['config']);
274 }
275 // Set the UI language of the editor if not hard-coded by the existing configuration
276 if (empty($configuration['language'])) {
277 $configuration['language'] = $this->getBackendUser()->uc['lang'] ?: ($this->getBackendUser()->user['lang'] ?: 'en');
278 }
279 $configuration['contentsLanguage'] = $this->getLanguageIsoCodeOfContent();
280
281 // replace all paths
282 $configuration = $this->replaceAbsolutePathsToRelativeResourcesPath($configuration);
283
284 // there are some places where we define an array, but it needs to be a list in order to work
285 if (is_array($configuration['extraPlugins'])) {
286 $configuration['extraPlugins'] = implode(',', $configuration['extraPlugins']);
287 }
288 if (is_array($configuration['removePlugins'])) {
289 $configuration['removePlugins'] = implode(',', $configuration['removePlugins']);
290 }
291 if (is_array($configuration['removeButtons'])) {
292 $configuration['removeButtons'] = implode(',', $configuration['removeButtons']);
293 }
294
295 return $configuration;
296 }
297
298 /**
299 * @param string $itemFormElementName
300 * @return string
301 */
302 protected function sanitizeFieldId(string $itemFormElementName): string
303 {
304 $fieldId = preg_replace('/[^a-zA-Z0-9_:.-]/', '_', $itemFormElementName);
305 return htmlspecialchars(preg_replace('/^[^a-zA-Z]/', 'x', $fieldId));
306 }
307
308 /**
309 * @return BackendUserAuthentication
310 */
311 protected function getBackendUser()
312 {
313 return $GLOBALS['BE_USER'];
314 }
315 }